home *** CD-ROM | disk | FTP | other *** search
/ Mac Magazin/MacEasy 12 / Mac Magazin and MacEasy Magazine CD - Issue 12.iso / Sharewarebibliothek / Anwendungen / Wissenschaft & Technik / Yorick / yorick11-ppc folder / startup / std.i < prev    next >
Text File  |  1995-07-11  |  107KB  |  2,646 lines

  1. /*
  2.     STD.I
  3.     Declarations of standard Yorick functions.
  4.  
  5.     $Id: std.i,v 1.1 1993/08/27 18:32:09 munro Exp munro $
  6.  
  7.     The Codger automatic code generator program uses this file to
  8.     generate appropriate C code to initialize the various built-in
  9.     functions declared here.
  10.     This file is also used as online documentation for these functions
  11.     by Yorick's help mechanism.
  12.  
  13.     The "extern" declaration of each function or variable is a no-op,
  14.     but causes Yorick to place the variable in the sourceList for this
  15.     include file, making it available for online help.  The DOCUMENT
  16.     comment is provided in a standard format to simplify manipulation
  17.     of such comments by programs other than Yorick;  it should immediately
  18.     follow the corresponding "extern" so that it will be visible when
  19.     the page containing the "extern" is displayed.
  20.  
  21.     The Codger code generator finds each "extern" line and creates
  22.     initialization code binding the associated Yorick variable to
  23.     either a BuiltIn function (see ydata.h) Y_variable, or, if a
  24.     "reshape, variable, ..." declaration is found, to a global
  25.     compiled variable y_variable with the compiled data type
  26.     corresponding to the Yorick data type mentioned in the "reshape"
  27.     command.  Codger can generate certain simple Y_variable wrapper
  28.     routines if further information is provided in a PROTOTYPE comment.
  29.  */
  30. /*    Copyright (c) 1994.  The Regents of the University of California.
  31.                     All rights reserved.  */
  32.  
  33. extern help;
  34. /* DOCUMENT help, topic
  35.          or help
  36.      Prints DOCUMENT comment from include file in which the variable
  37.      TOPIC was defined, followed by the line number and filename.
  38.      By opening the file with a text editor, you may be able to find
  39.      out more, especially if no DOCUMENT comment was found.
  40.      Examples:
  41.        help, set_path
  42.      prints the documentation for the set_path function.
  43.        help
  44.      prints the DOCUMENT comment you are reading.
  45.  
  46.      This copy of Yorick was launched from the directory:
  47.      **** Y_LAUNCH (computed at runtime) ****
  48.      Yorick's "site directory" at this site is:
  49.      **** Y_SITE (computed at runtime) ****
  50.      You can find out a great deal more about Yorick by browsing
  51.      through these directories.  Begin with the site directory,
  52.      and pay careful attention to the subdirectories doc/ (which
  53.      contains documentation relating to Yorick), and include/ and
  54.      contrib/ (which contain many examples of Yorick programs).
  55.      Look for files called README (or something similar) in any
  56.      of these directories -- they are intended to assist browsers.
  57.      The site directory itself contains std.i and graph.i, which
  58.      are worth reading.
  59.  
  60.      Type:
  61.        help, dbexit
  62.      for help on debug mode.  If your prompt is "dbug>" instead of
  63.      ">", dbexit will return you to normal mode.
  64.  
  65.    SEE ALSO: info, print, copyright, warranty, legal
  66.  */
  67.  
  68. local copyright, warranty;
  69. /* DOCUMENT copyright, (no) warranty
  70.  
  71.      Copyright (c) 1994.  The Regents of the University of California.
  72.                    All rights reserved.
  73.  
  74.      Yorick is provided "as is" without any warranty, either expressed or
  75.      implied.  For a complete statement, type:
  76.  
  77.         legal
  78.  
  79.      at the Yorick prompt.
  80.  
  81.    SEE ALSO: legal
  82.  */
  83.  
  84. func legal(void)
  85. /* DOCUMENT legal
  86.      Prints the legal details of Yorick's copyright, licensing,
  87.      and lack of warranty.
  88.    SEE ALSO: copyright, warranty
  89.  */
  90. {
  91.   require, "legal.i";
  92.   raw_legal;
  93. }
  94.  
  95. func help_worker
  96. /* xxDOCUMENT help_worker (Not for interactive use -- called by help.)
  97.  */
  98. {
  99.   /* help_worker task is pushed by help function -- topic and file
  100.      arguments are left in help_topic and help_file variables */
  101.   topic= help_topic;   help_topic= [];
  102.   file= help_file;     help_file= [];
  103.  
  104.   if (file) {
  105.     mark= bookmark(file);
  106.     line= rdline(file);
  107.  
  108.     if (typeof(topic)!="struct_definition") {
  109.       /* non-struct looks for DOCUMENT comment before any blank lines */
  110.       n= 10;   /* read at most 10 lines looking for DOCUMENT comment */
  111.       while (strtok(line)(1) && n--) {
  112.     if (strmatch(line, "/* DOCUMENT")) break;
  113.     line= rdline(file);
  114.       }
  115.       if (strmatch(line, "/* DOCUMENT")) {
  116.     do {
  117.       if (strmatch(line, "**** Y_LAUNCH (computed at runtime) ****"))
  118.         write, "      "+Y_LAUNCH;
  119.       else if (strmatch(line, "**** Y_SITE (computed at runtime) ****"))
  120.         write, "      "+Y_SITE;
  121.       else
  122.         write, line;
  123.       line= rdline(file);
  124.       if (!line) break;
  125.     } while (!strmatch(line, "*/"));
  126.     write, line;
  127.       } else {
  128.     write, "<DOCUMENT comment not found>";
  129.       }
  130.  
  131.     } else {
  132.       /* struct just prints definition */
  133.       gotopen= 0;
  134.       do {
  135.     if (!gotopen) gotopen= strmatch(line, "{");
  136.     write, line;
  137.     if (gotopen && strmatch(line, "}")) break;
  138.       } while (line= rdline(file));
  139.     }
  140.  
  141.     write, "defined at:"+print(mark)(2);
  142.  
  143.   } else {
  144.     write, "<not defined in an include file, running info function>";
  145.     info, topic;
  146.   }
  147. }
  148.  
  149. func info(topic)
  150. /* DOCUMENT info, expr
  151.      prints the data type and array dimensions of EXPR.
  152.    SEE ALSO: help, print
  153.  */
  154. {
  155.   if (is_array(topic)) {
  156.     void= use_origins(1);  /* assure NON-forced origin */
  157.     line= "array(" + nameof(structof(topic));
  158.     dims= dimsof(topic);
  159.     orgs= orgsof(topic);
  160.     ndims= dims(1)+1;
  161.     for (i=2 ; i<=ndims ; i++) {
  162.       line+= ",";
  163.       if (orgs(i)!=1)
  164.     line+= print(orgs(i))(1)+":"+print(orgs(i)+dims(i)-1)(1);
  165.       else
  166.     line+= print(dims(i))(1);
  167.     }
  168.     line+= ")";
  169.     write, line;
  170.   } else {
  171.     print, topic;
  172.   }
  173. }
  174.  
  175. /*--------------------------------------------------------------------------*/
  176.  
  177. extern quit;
  178. /* DOCUMENT quit
  179.      Exit YMainLoop when current task finishes.
  180.      Normally this terminates the program.
  181.  */
  182.  
  183. extern system;
  184. /* DOCUMENT system, "shell command line"
  185.      Passes the command line string to a shell for execution.
  186.      If the string is constant, you may use the special syntax:
  187.          $shell command line
  188.      (A long command line may be continued by ending the line with \
  189.      as usual.)  The system function syntax allows Yorick to compute
  190.      parts of the command line string, while the simple $ escape
  191.      syntax does not.  In either case, the only way to get output
  192.      back from such a command is to redirect it to a file, then
  193.      read the file.  Note that Yorick does not regain control
  194.      until the subordinate shell finishes.  (Yorick will get control
  195.      back if the command line backgrounds the job.)
  196.  */
  197.  
  198. extern yorick_init;
  199. /* xxDOCUMENT yorick_init
  200.      Re-initializes all of the built-in functions for this version
  201.      of Yorick.  To be used in desperation if you overwrite some
  202.      critical built-in function by mistake.  Of course, if you
  203.      redefine yorick_init, you won't be able to recover anything.
  204.  */
  205.  
  206. extern set_path;
  207. /* DOCUMENT set_path, "dir1:dir2:dir3:..."
  208.          or set_path
  209.      sets the include file search path to the specified list of
  210.      directories.  The specified directories are searched left to
  211.      right for include files specified as relative file names in
  212.      #include directives, or to the include or require functions.
  213.      If the argument is omitted, restores the default search path,
  214.      ".:~/Yorick:Y_LAUNCH/include:Y_SITE/include:Y_SITE/contrib",
  215.      where y_site is the main Yorick directory for this site.
  216.      The Y_LAUNCH directory is the directory which contains the
  217.      executable; this directory is omitted if it is the same as
  218.      Y_SITE.
  219.  
  220.      Only the "end user" should ever call set_path, and then only in
  221.      his or her custom.i file, for the purpose of placing a more
  222.      elaborate set of personal directories containing Yorick procedures.
  223.      For example, if someone else maintains Yorick code you use, you
  224.      might put their ~/Yorick on your include path.
  225.  
  226.    SEE ALSO: Y_LAUNCH, Y_SITE, include, require
  227.  */
  228.  
  229. extern set_site;
  230. /* xxDOCUMENT set_site, site_directory
  231.      sets Y_LAUNCH, Y_SITE as a side effect.  Should only be called from
  232.      paths.i, and is never called by default.  See paths.i.  */
  233.  
  234. extern yorick_stats;
  235. /* DOCUMENT yorick_stats
  236.      returns an array of longs describing Yorick memory usage.
  237.      For debugging.  See ydata.c source code.
  238.  */
  239.  
  240. extern disassemble;
  241. /* DOCUMENT disassemble(function)
  242.          or disassemble, function
  243.      Disassembles the specified function.  If called as a function, the
  244.      result is returned as a vector of strings; if called as a subroutine,
  245.      the disassembly is printed at the terminal.  If the function is nil,
  246.      the current *main* program is disassembled -- you must include the
  247.      call to disassemble in the main program, of course, NOT on its own
  248.      line as a separate main program.
  249.  */
  250.  
  251. extern reshape;
  252. /* DOCUMENT reshape, reference, address, type, dimension_list
  253.          or reshape, reference, type, dimension_list
  254.          or reshape, reference
  255.      The REFERENCE must be an unadorned variable, not an expression;
  256.      reshape sets this variable to an LValue at the specified ADDRESS
  257.      with the specified TYPE and DIMENSION_LIST.  (See the array
  258.      function documentation for acceptable DIMENSION_LIST formats.)
  259.      If ADDRESS is an integer (e.g.- a long), the programmer is
  260.      responsible for assuring that the data at ADDRESS is valid.
  261.      If ADDRESS is a (Yorick) pointer, Yorick will assure that the
  262.      data pointed to will not be discarded, and the reshape will
  263.      fail if TYPE and DIMENSION_LIST extend beyond the pointee
  264.      bounds.  In the second form, ADDRESS is taken to be &REFERENCE;
  265.      that is, the TYPE and DIMENSION_LIST of the variable are changed
  266.      without doing any type conversion.  In the third form, REFERENCE
  267.      is set to nil ([]).  (Simple redefinition will not work on a
  268.      variable defined using reshape.)
  269.   SEE ALSO: array, dimsof, numberof, is_array
  270.  */
  271.  
  272. /*--------------------------------------------------------------------------*/
  273.  
  274. extern array;
  275. /* DOCUMENT array(value, dimension_list)
  276.          or array(type, dimension_list)
  277.      returns an object of the same type as VALUE, consisting of copies
  278.      of VALUE, with the given DIMENSION_LIST appended to the dimensions
  279.      of VALUE.  Hence, array(1.5, 3, 1) is the same as [[1.5, 1.5, 1.5]].
  280.      In the second form, the VALUE is taken as scalar zero of the TYPE.
  281.      Hence, array(short, 2, 3) is the same as [[0s,0s],[0s,0s],[0s,0s]].
  282.      A DIMENSION_LIST is a list of arguments, each of which may be
  283.      any of the following:
  284.         (1) A positive scalar integer expression,
  285.     (2) An index range with no step field (e.g.-  1:10), or
  286.     (3) A vector of integers [number of dims, length1, length2, ...]
  287.         (that is, the format returned by the dimsof function).
  288.   SEE ALSO: reshape, is_array, dimsof, numberof, grow, span, use_origins
  289.  */
  290.  
  291. /*--------------------------------------------------------------------------*/
  292.  
  293. extern structof;
  294. /* DOCUMENT structof(object)
  295.      returns the data type of OBJECT, or nil for non-array OBJECTs.
  296.      Use typeof(object) to get the ASCII name of a the data type.
  297.   SEE ALSO: typeof, dimsof, numberof, sizeof, nameof
  298.  */
  299.  
  300. extern dimsof;
  301. /* DOCUMENT dimsof(object)
  302.          or dimsof(object1, object2, ...)
  303.      returns a vector of integers describing the dimensions of OBJECT.
  304.      The format of the vector is [number of dims, length1, length2, ...].
  305.      The orgsof function returns the origin of each dimension (normally 1).
  306.      If more than one argument is given, dimsof returns the dimension
  307.      list of the result of binary operations between all the objects,
  308.      or nil if the objects are not conformable.
  309.   SEE ALSO: typeof, structof, numberof, sizeof, orgsof
  310.  */
  311.  
  312. extern orgsof;
  313. /* DOCUMENT orgsof(object)
  314.      returns a vector of integers describing the dimensions of OBJECT.
  315.      The format of the vector is [number of dims, origin1, origin2, ...].
  316.      By default, dimension origins are ignored, but use_origins changes
  317.      this.  The dimsof function returns the length of each dimension.
  318.      *** NOTE NOTE NOTE ***
  319.      Unless use_origins(1) is in effect, orgsof will always return
  320.      1 for all of the originI in the list.  Thus, whether use_origins(1)
  321.      is in effect or not, you are guaranteed that x(orgsof(x)(2)) is the
  322.      first element of x.
  323.   SEE ALSO: dimsof, typeof, structof, numberof, sizeof, use_origins
  324.  */
  325.  
  326. extern use_origins;
  327. /* DOCUMENT dummy= use_origins(dont_force)
  328.      Yorick array dimensions have an origin as well as a length.
  329.      By default, this origin is 1 (like FORTRAN arrays, unlike C
  330.      arrays).  However, the array function and the pseudo-index (-)
  331.      can be used to produce arrays with other origins.
  332.  
  333.      Initially, the origin of an array index is ignored by Yorick; the
  334.      first element of any array has index 1.  You can change this
  335.      default behavior by calling use_origins with non-zero DONT_FORCE,
  336.      and restore the default behavior by calling use_origins(0).
  337.  
  338.      When the returned object DUMMY is destroyed, either by return from
  339.      the function in which it is a local variable, or by explicit
  340.      redefintion of the last reference to it, the treatment of array
  341.      index origins reverts to the behavior prior to the call to
  342.      use_origins.  Thus, you can call use_origins at the top of a
  343.      function and not worry about restoring the external behavior
  344.      before every possible return (including errors).
  345.  
  346.   SEE ALSO: array, dimsof, orgsof
  347.  */
  348.  
  349. extern sizeof;
  350. /* DOCUMENT sizeof(object)
  351.      returns the size of the object in bytes, or 0 for non-array objects.
  352.      sizeof(structure_definition) returns the number of bytes per instance.
  353.   SEE ALSO: dimsof, typeof, structof, numberof
  354.  */
  355.  
  356. extern numberof;
  357. /* DOCUMENT numberof(object)
  358.      returns the number of elements if object is an array, or 0 if not.
  359.   SEE ALSO: sizeof, dimsof, typeof, structof
  360.  */
  361.  
  362. extern typeof;
  363. /* DOCUMENT typeof(object)
  364.      returns a string describing the type of object.  For the basic
  365.      data types, these are "char", "short", "int", "long", "float",
  366.      "double", "complex", "string", "pointer", "struct_instance",
  367.      "void", "range", "struct_definition", "function", "builtin",
  368.      and "stream".
  369.   SEE ALSO: structof, dimsof, sizeof, numberof, nameof
  370.  */
  371.  
  372. extern nameof;
  373. /* DOCUMENT nameof(object)
  374.      If OBJECT is a function or a structure definition, returns the
  375.      name of the func or struct as it was defined (not necessarily
  376.      the name of the variable passed to the nameof function).
  377.   SEE ALSO: typeof
  378.  */
  379.  
  380. /*--------------------------------------------------------------------------*/
  381.  
  382. extern print;
  383. /* DOCUMENT print, object1, object2, object3, ...
  384.          or print(object1, object2, object3, ...)
  385.      prints an ASCII representation of the OBJECTs, in roughly the format
  386.      they could appear in Yorick source code.  When invoked as a subroutine
  387.      (in the first form), output is to the terminal.  When invoked as a
  388.      function (int the second form), the output is stored as a vector of
  389.      strings, one string per line that would have been output.
  390.      Printing a structure definition prints the structure definition;
  391.      printing a function prints its "func" definition; printing files,
  392.      bookmarks, and other objects generally provides some sort of
  393.      useful description of the object.
  394.   SEE ALSO: pr1, print_format, write, exit, error, nameof, typeof
  395.  */
  396.  
  397. func pr1(x)
  398. /* DOCUMENT pr1(x)
  399.      returns text representing expression X, equivalent to print(X)(1).
  400.    SEE ALSO: print, swrite
  401.  */
  402. { return print(x)(1); }
  403.  
  404. extern print_format;
  405. /* DOCUMENT print_format, line_length, char=, short=, int=, float=,
  406.                           double=, complex=, pointer=
  407.      sets the format string the print function will use for each of
  408.      the basic data types.  Yorick format strings are the same as the
  409.      format strings for the printf function defined in the ANSI C standard.
  410.      The default strings may be restored individually by setting the
  411.      associated format string to ""; all defaults are restored if
  412.      print_format is invoked with no arguments.  The default format strings
  413.      are:  "0x%02x", "%d", "%d", "%ld", "%g", "%g", and "%g%+gi".
  414.      Note that char and short values are converted to int before being
  415.      passed to printf, and that float is converted to double.
  416.      If present, an integer positional argument is taken as the line
  417.      length; <=0 restores the default line length of 80 characters.
  418.   SEE ALSO: print, write, nameof, typeof
  419.  */
  420.  
  421. /*--------------------------------------------------------------------------*/
  422.  
  423. extern is_array;
  424. /* DOCUMENT is_array(object)
  425.      returns 1 if OBJECT is an array data type (as opposed to a function,
  426.      structure definition, index range, I/O stream, etc.), else 0.
  427.      An array OBJECT can be written to or read from a binary file;
  428.      non-array Yorick data types cannot.
  429.   SEE ALSO: is_func, is_void, is_range, is_struct, is_stream
  430.  */
  431.  
  432. extern is_func;
  433. /* DOCUMENT is_func(object)
  434.      returns 1 if OBJECT is a Yorick interpreted function, 2 if OBJECT
  435.      is a built-in (that is, compiled) function, else 0.
  436.   SEE ALSO: is_array, is_void, is_range, is_struct, is_stream
  437.  */
  438.  
  439. extern is_void;
  440. /* DOCUMENT is_void(object)
  441.      returns 1 if OBJECT is nil (the one instance of the void data type),
  442.      else 0.
  443.   SEE ALSO: is_array, is_func, is_range, is_struct, is_stream
  444.  */
  445.  
  446. extern is_range;
  447. /* DOCUMENT is_range(object)
  448.      returns 1 if OBJECT is an index range (e.g.-  3:5 or 11:31:2),
  449.      else 0.
  450.   SEE ALSO: is_array, is_func, is_void, is_struct, is_stream
  451.  */
  452.  
  453. extern is_struct;
  454. /* DOCUMENT is_struct(object)
  455.      returns 1 if OBJECT is the definition of a Yorick struct, else 0.
  456.      Thus, is_struct(double) returns 1, but is_struct(1.0) returns 0.
  457.   SEE ALSO: is_array, is_func, is_void, is_range, is_stream
  458.  */
  459.  
  460. extern is_stream;
  461. /* DOCUMENT is_stream(object)
  462.      returns 1 if OBJECT is an I/O stream (usually a file), else 0.
  463.   SEE ALSO: is_array, is_func, is_void, is_range, is_struct
  464.  */
  465.  
  466. /*--------------------------------------------------------------------------*/
  467.  
  468. extern am_subroutine;
  469. /* DOCUMENT am_subroutine()
  470.      returns 1 if the current Yorick function was invoked as a subroutine,
  471.      else 0.  If am_subroutine() returns true, the result of the current
  472.      function will not be used, and need not be computed (the function
  473.      has been called for its side effects only).
  474.  */
  475.  
  476. /*--------------------------------------------------------------------------*/
  477.  
  478. extern sin;
  479. extern cos;
  480. extern tan;
  481. /* DOCUMENT sin(x)
  482.             cos(x)
  483.             tan(x)
  484.      returns the sine, cosine, or tangent of its argument,
  485.      which is in radians.
  486.   SEE ALSO: asin, acos, atan
  487.  */
  488.  
  489. extern asin;
  490. /* DOCUMENT asin(x)
  491.      returns the inverse sine of its argument, range [-pi/2, pi/2].
  492.   SEE ALSO: sin, cos, tan, asin, acos, atan
  493.  */
  494.  
  495. extern acos;
  496. /* DOCUMENT acos(x)
  497.      returns the inverse cosine of its argument, range [0, pi].
  498.   SEE ALSO: sin, cos, tan, asin, acos, atan
  499.  */
  500.  
  501. extern atan;
  502. /* DOCUMENT atan(x)
  503.          or atan(y, x)
  504.      returns the inverse tangent of its argument, range [-pi/2, pi/2].
  505.      In the two argument form, returns the angle from (1, 0) to (x, y),
  506.      in the range (-pi, pi], with atan(1, 0)==pi/2.  (If x>=0, this is
  507.      the same as atan(y/x).)
  508.   SEE ALSO: sin, cos, tan, asin, acos, atan
  509.  */
  510.  
  511. local pi;
  512. /* DOCUMENT pi
  513.      roughly 3.14159265358979323846264338327950288
  514.  */
  515. pi= 4.0*atan(1.0);    /* to double precision on this machine */
  516.  
  517. extern sinh;
  518. extern cosh;
  519. extern tanh;
  520. /* DOCUMENT sinh(x)
  521.             cosh(x)
  522.             tanh(x)
  523.      returns the hyperbolic sine, cosine, or tangent of its argument.
  524.   SEE ALSO: sech, csch, asinh, acosh, atanh
  525.  */
  526.  
  527. func sech(x) { y= tanh(x);  return sqrt(1.0-y*y); }
  528. func csch(x) { y= 1.0/tanh(x);  return sqrt(y*y-1.0); }
  529. /* DOCUMENT sech(x)
  530.             csch(x)
  531.      returns the hyperbolic secant (1/cosh) or cosecant (1/sinh) of
  532.      its argument, without overflowing for large x.
  533.   SEE ALSO: sinh, cosh, tanh, asinh, acosh, atanh
  534.  */
  535.  
  536. func asinh(x) { return log(x+sqrt(x*x+1.0)); }
  537. func acosh(x) { return log(x+sqrt(x*x-1.0)); }
  538. func atanh(x) { return 0.5*log((1.0+x)/(1.0-x)); }
  539. /* DOCUMENT asinh(x)
  540.             acosh(x)
  541.             atanh(x)
  542.      returns the inverse hyperbolic sine, cosine, or tangent of
  543.      its argument.  The range of acosh is >=0.0.
  544.   SEE ALSO: sinh, cosh, tanh, sech, csch
  545.  */
  546.  
  547. extern exp;
  548. /* DOCUMENT exp(x)
  549.      returns the exponential function of its argument (inverse of log).
  550.   SEE ALSO: log, log10, sinh, cosh, tanh, sech, csch
  551.  */
  552.  
  553. extern log;
  554. /* DOCUMENT log(x)
  555.      returns the natural logarithm of its argument (inverse of exp).
  556.   SEE ALSO: log10, exp, asinh, acosh, atanh
  557.  */
  558.  
  559. extern log10;
  560. /* DOCUMENT log10(x)
  561.      returns the base 10 logarithm of its argument (inverse of 10^x).
  562.   SEE ALSO: log, exp, asinh, acosh, atanh
  563.  */
  564.  
  565. extern sqrt;
  566. /* DOCUMENT sqrt(x)
  567.      returns the square root of its argument.
  568.   SEE ALSO: abs, also note the rms range function
  569.  */
  570.  
  571. extern poly;
  572. /* DOCUMENT poly(x, a0, a1, a2, ..., aN)
  573.      returns the polynomial  A0 + A1*x + A2*x^2 + ... + AN*X^N
  574.      The data type and dimensions of the result, and conformability rules
  575.      for the inputs are identical to those for the expression.
  576.  */
  577.  
  578. extern ceil;
  579. /* DOCUMENT ceil(x)
  580.      returns the smallest integer not less than x (no-op on integers).
  581.   SEE ALSO: floor
  582.  */
  583.  
  584. extern floor;
  585. /* DOCUMENT floor(x)
  586.      returns the largest integer not greater than x (no-op on integers).
  587.   SEE ALSO: ceil
  588.  */
  589.  
  590. extern abs;
  591. /* DOCUMENT abs(x)
  592.          or abs(x, y, z, ...)
  593.      returns the absolute value of its argument.
  594.      In the multi-argument form, returns sqrt(x^2+y^2+z^2+...).
  595.   SEE ALSO: sign, sqrt, also note the rms range function
  596.  */
  597.  
  598. extern sign;
  599. /* DOCUMENT sign(x)
  600.      returns algebraic sign of it argument, or closest point on the
  601.      unit circle for complex x.  Guaranteed that x==sign(x)*abs(x).
  602.      sign(0)==+1.
  603.   SEE ALSO: abs
  604.  */
  605.  
  606. extern conj;
  607. /* DOCUMENT conj(x)
  608.      returns the complex conjugate of its argument.
  609.  */
  610.  
  611. extern random;
  612. extern random_seed;
  613. /* DOCUMENT random(dimension_list)
  614.             random_seed, seed
  615.      returns an array of random double values with the given
  616.      DIMENSION_LIST (nil for a scalar result), uniformly distributed
  617.      on the interval from 0.0 to 1.0.
  618.      The algorithm is from Press and Teukolsky, Computers in Physics,
  619.      vol. 6, no. 5, Sep/Oct 1992 (ran2).  They offer a reward of $1000
  620.      to anyone who can exhibit a statistical test that this random
  621.      number generator fails in a "non-trivial" way.
  622.      The random_seed call reinitializes the random number sequence;
  623.      SEED should be between 0.0 and 1.0 non-inclusive; if SEED is
  624.      omitted, nil, or out of range, the sequence is reinitialized as
  625.      when Yorick starts.
  626.      The numbers are actually at the centers of 2147483562 equal width
  627.      bins on the interval [0,1].  Although only these 2 billion numbers
  628.      are possible, the period of the generator is roughly 2.3e18.
  629.  
  630.    SEE ALSO: randomize
  631.  */
  632.  
  633. func randomize(void)
  634. /* DOCUMENT randomize
  635.             randomize()
  636.      set the seed for random "randomly" (based on the timer clock
  637.      and the current state of random).  As a function, returns the
  638.      value of the seed passed to random_seed.
  639.  
  640.    SEE ALSO: random, random_seed
  641.  */
  642. {
  643.   seed= array(0., 3);
  644.   timer, seed;
  645.   seed= pi*sum(abs(seed));
  646.   while (seed > 0.9) seed*= 0.1;
  647.   seed+= 0.05;
  648.   random_seed, seed;
  649.   return seed;
  650. }
  651.  
  652. /*--------------------------------------------------------------------------*/
  653.  
  654. extern min;
  655. /* DOCUMENT min(x)
  656.          or min(x, y, z, ...)
  657.      returns the scalar minimum value of its array argument, or, if
  658.      more than one argument is supplied, returns an array of the
  659.      minimum value for each array element among the several arguments.
  660.      In the multi-argument case, the arguments must be conformable.
  661.   SEE ALSO: max, sum, avg
  662.  */
  663.  
  664. extern max;
  665. /* DOCUMENT max(x)
  666.          or max(x, y, z, ...)
  667.      returns the scalar maximum value of its array argument, or, if
  668.      more than one argument is supplied, returns an array of the
  669.      maximum value for each array element among the several arguments.
  670.      In the multi-argument case, the arguments must be conformable.
  671.   SEE ALSO: min, sum, avg
  672.  */
  673.  
  674. extern sum;
  675. /* DOCUMENT sum(x)
  676.      returns the scalar sum of all elements of its array argument.
  677.   SEE ALSO: avg, min, max
  678.  */
  679.  
  680. extern avg;
  681. /* DOCUMENT avg(x)
  682.      returns the scalar average of all elements of its array argument.
  683.   SEE ALSO: sum, min, max
  684.  */
  685.  
  686. extern allof;
  687. extern anyof;
  688. extern noneof;
  689. extern nallof;
  690. /* DOCUMENT allof(x)
  691.             anyof(x)
  692.             nallof(x)
  693.             noneof(x)
  694.      Respectively:
  695.       returns 1 if every element of the array x is non-zero, else 0.
  696.       returns 1 if at least one element of the array x is non-zero, else 0.
  697.       returns 1 if at least one element of the array x is zero, else 0.
  698.       returns 1 if every element of the array x is zero, else 0.
  699.   SEE ALSO: allof, anyof, noneof, nallof, where, where2
  700.  */
  701.  
  702. extern where;
  703. /* DOCUMENT where(x)
  704.      returns the vector of longs which is the index list of non-zero
  705.      values in the array x.  Thus, where([[0,1,3],[2,0,4]]) would
  706.      return [2,3,4,6].  If noneof(x), where(x) is a special range
  707.      function which will return a nil value if used to index an array;
  708.      hence, if noneof(x), then x(where(x)) is nil.
  709.      If x is a non-zero scalar, then where(x) returns a scalar value.
  710.      The rather recondite behavior for scalars and noneof(x) provides
  711.      maximum performance when the merge function to be used with the
  712.      where function.
  713.   SEE ALSO: where2, merge, merge2 allof, anyof, noneof, nallof, sort
  714.  */
  715.  
  716. func where2(x)
  717. /* DOCUMENT where2(x)
  718.      like where(x), but the returned list is decomposed into indices
  719.      according to the dimensions of x.  The returned list is always
  720.      2 dimensional, with the second dimension the same as the dimension
  721.      of where(x).  The first dimension has length corresponding to the
  722.      number of dimensions of x.  Thus, where2([[0,1,3],[2,0,4]]) would
  723.      return [[2,1],[3,1],[1,2],[3,2]].
  724.      If noneof(x), where2 returns [] (i.e.- nil).
  725.   SEE ALSO: where, merge, merge2, allof, anyof, noneof, nallof, sort
  726.  */
  727. {
  728.   w= where(x);
  729.   /* Since the result of where2 cannot be used as an index list, the
  730.      case noneof(x) can be disposed of more easily than with where.  */
  731.   if (!is_array(w)) return [];
  732.   d= dimsof(x);
  733.   n= d(1);
  734.   if (!n) return w;  /* catcall for passing a scalar */
  735.   d= d(2:);
  736.   o= orgsof(x)(2:);
  737.   w2= w(-:1:n,);
  738.   w-= o(1);
  739.   for (i=1 ; i<=n ; i++) {
  740.     w2(i,)= w%d(i) + o(i);
  741.     w/= d(i);
  742.   }
  743.   return w2;
  744. }
  745.  
  746. extern merge;
  747. /* DOCUMENT merge(true_expr, false_expr, condition)
  748.      returns the values TRUE_EXPR or FALSE_EXPR where CONDITION is
  749.      non-zero or zero, respectively.  The result has the data type of
  750.      TRUE_EXPR or FALSE_EXPR, promoted to the higher arithmetic type
  751.      if necessary.  The result has the dimensions of CONDITION.
  752.      The number of elements in TRUE_EXPR must match the number of
  753.      non-zero elements of CONDITION, and the number of elements in
  754.      FALSE_EXPR must match the number of zero elements of CONDITION.
  755.      (TRUE_EXPR or FALSE_EXPR should be nil if there are no such
  756.      elements of CONDITION.  Normally, TRUE_EXPR and FALSE_EXPR should
  757.      be 1-D arrays if they are not nil.)
  758.      This function is intended for vectorizing a function whose
  759.      domain is divided into two or more parts, as in:
  760.         func f(x) {
  761.       big= (x>=threshhold);
  762.       wb= where(big);
  763.       ws= where(!big);
  764.       if (is_array(wb)) {
  765.         xx= x(wb);
  766.         fb= <function of xx>
  767.       }
  768.       if (is_array(ws)) {
  769.         xx= x(ws);
  770.         fs= <function of xx>
  771.       }
  772.       return merge(fb, fs, big);
  773.     }
  774.    SEE ALSO: merge2, where
  775.  */
  776.  
  777. func merge2(t, f, c)
  778. /* DOCUMENT merge2(true_expr, false_expr, condition)
  779.      returns the values TRUE_EXPR or FALSE_EXPR where CONDITION is
  780.      non-zero or zero, respectively.  The result has the data type of
  781.      TRUE_EXPR or FALSE_EXPR, promoted to the higher arithmetic type
  782.      if necessary.  Unlike the merge function, TRUE_EXPR and FALSE_EXPR
  783.      must be conformable with each other, and with the CONDITION.
  784.    SEE ALSO: merge2, where
  785.  */
  786. {
  787.   dims= dimsof(t, f, c);
  788.   if (dims(1)) {
  789.     c+= array(structof(c), dims);
  790.     tt= array(structof(t), dims);  tt(..)= t;
  791.     ff= array(structof(f), dims);  ff(..)= f;
  792.   } else {
  793.     tt= t;
  794.     ff= f;
  795.   }
  796.   return merge(tt(where(c)), ff(where(!c)), c);
  797. }
  798.  
  799. /*--------------------------------------------------------------------------*/
  800.  
  801. extern grow;
  802. extern _;
  803. /* DOCUMENT grow, x, xnext1, xnext2, ...
  804.          or grow(x, xnext1, xnext2, ...)
  805.      or    _(x, xnext1, xnext2, ...)
  806.      lengthens the array X by appending XNEXT1, XNEXT2, etc. to its
  807.      final dimension.  If X is nil, X is first redefined to the first
  808.      non-nil XNEXT, and the remainder of the XNEXT list is processed
  809.      normally.  Each XNEXT is considered to have the same number of
  810.      dimensions as X, by appending unit-length dimensions if necessary.
  811.      All but this final dimension of each XNEXT must be right-conformable
  812.      (that is, conformable in the sense of the right hand side of an
  813.      assignment statement) with all but the final dimension of X.
  814.      The result has a final dimension which is the sum of the final
  815.      dimension of X and all the final dimensions of the XNEXT.  Nil
  816.      XNEXT are ignored.  The value of the result is obtained by
  817.      concatenating all the XNEXT to X, after any required broadcasts.
  818.  
  819.      If invoked as a function, grow returns the new value of X; in
  820.      this case, X may be an expression.  X must be a simple variable
  821.      reference for the subroutine form of grow; otherwise there is
  822.      nowhere to return the result.  The subroutine form is slightly
  823.      more efficient than the function form for the common usage:
  824.           x= grow(x, xnext1, xnext2)           is the same as
  825.       grow, x, xnext1, xnext2              the preferred form
  826.  
  827.      The _ function is a synonym for grow, for people who want this
  828.      operator to look like punctuation in their source code, on analogy
  829.      with the array building operator [a, b, c, ...].
  830.    SEE ALSO: array, compare with the array building operator [...]
  831.  */
  832.  
  833. extern indgen;
  834. /* DOCUMENT indgen(n)
  835.          or indgen(start:stop)
  836.          or indgen(start:stop:step)
  837.      returns "index generator" list -- an array of longs running from
  838.      1 to N, inclusive.  In the second and third forms, the index
  839.      values specified by the index range are returned.
  840.    SEE ALSO: span, spanl, array
  841.  */
  842.  
  843. extern span;
  844. /* DOCUMENT span(start, stop, n)
  845.          or span(start, stop, n, which)
  846.      returns array of N doubles equally spaced from START to STOP.
  847.      The START and STOP arguments may themselves be arrays, as long as
  848.      they are conformable.  In this case, the result will have one
  849.      dimension of length N in addition to dimsof(START, STOP).
  850.      By default, the result will be N-by-dimsof(START, STOP), but
  851.      if WHICH is specified, the new one of length N will be the
  852.      WHICHth.  WHICH may be non-positive to position the new
  853.      dimension relative to the end of dimsof(START, STOP); in
  854.      particular WHICH of 0 produces a result with dimensions
  855.      dimsof(START, STOP)-by-N.
  856.    SEE ALSO: spanl, indgen, array
  857.  */
  858.  
  859. func spanl(start, stop, n, which)
  860. /* DOCUMENT spanl(start, stop, n)
  861.          or spanl(start, stop, n, which)
  862.      similar to the span function, but the result array have N points
  863.      spaced at equal ratios from START to STOP (that is, equally
  864.      spaced logarithmically).  See span for discussion of WHICH argument.
  865.      START and STOP must have the same algebraic sign for this to make
  866.      any sense.
  867.    SEE ALSO: span, indgen, array
  868.  */
  869. {
  870.   return exp(span(log(abs(start)), log(abs(stop)), n,
  871.           (is_void(which)? 1 : which)))*sign(start);
  872. }
  873.  
  874. extern digitize;
  875. /* DOCUMENT digitize(x, bins)
  876.      returns an array of longs with dimsof(X), and values i such that
  877.      BINS(i-1) <= X < BINS(i) if BINS is monotonically increasing, or
  878.      BINS(i-1) > X >= BINS(i) if BINS is monotonically decreasing.
  879.      Beyond the bounds of BINS, returns either i=1 or i=numberof(BINS)+1
  880.      as appropriate.
  881.    SEE ALSO: histogram, interp, integ, sort, where, where2
  882.  */
  883.  
  884. extern histogram;
  885. /* DOCUMENT histogram(list)
  886.          or histogram(list, weight)
  887.      returns an array hist which counts the number of occurrences of each
  888.      element of the input index LIST, which must consist of positive
  889.      integers (1-origin index values into the result array):
  890.           histogram(list)(i) = number of occurrences of i in LIST
  891.  
  892.      A second argument WEIGHT must have the same shape as LIST; the result
  893.      will be the sum of WEIGHT:
  894.           histogram(list)(i) = sum of all WEIGHT(j) where LIST(j)==i
  895.  
  896.      The result of the single argument call will be of type long; the
  897.      result of the two argument call will be of type double (WEIGHT is
  898.      promoted to that type).  The input argument(s) may have any number
  899.      of dimensions; the result is always 1-D.
  900.  
  901.    KEYWORD: top=max_list_value
  902.      By default, the length of the result is max(LIST).  You may
  903.      specify that the result have a larger length by means of the TOP
  904.      keyword.  (Elements beyond max(LIST) will be 0, of course.)
  905.  
  906.    SEE ALSO: digitize, sort
  907.  */
  908.  
  909. extern interp;
  910. /* DOCUMENT interp(y, x, xp)
  911.          or interp(y, x, xp, which)
  912.      returns yp such that (XP, yp) lies on the piecewise linear curve
  913.      (X(i), Y(i)) (i=1, ..., numberof(X)).  Points beyond X(1) are set
  914.      to Y(1); points beyond X(0) are set to Y(0).  The array X must be
  915.      one dimensional, have numberof(X)>=2, and be either monotonically
  916.      increasing or monotonically decreasing.  The array Y may have more
  917.      than one dimension, but dimension WHICH must be the same length as
  918.      X.  WHICH defaults to 1, the first dimension of Y.  WHICH may be
  919.      non-positive to count dimensions from the end of Y; a WHICH of 0
  920.      means the final dimension of Y.  The result yp has dimsof(XP)
  921.      in place of the WHICH dimension of Y (if XP is scalar, the WHICH
  922.      dimension is not present).  (The dimensions of the result are the
  923.      same as if an index list with dimsof(XP) were placed in slot
  924.      WHICH of Y.)
  925.    SEE ALSO: integ, digitize, span
  926.  */
  927.  
  928. extern integ;
  929. /* DOCUMENT integ(y, x, xp)
  930.          or integ(y, x, xp, which)
  931.      See the interp function for an explanation of the meanings of the
  932.      arguments.  The integ function returns ypi which is the integral
  933.      of the piecewise linear curve (X(i), Y(i)) (i=1, ..., numberof(X))
  934.      from X(1) to XP.  The curve (X, Y) is regarded as constant outside
  935.      the bounds of X.  Note that X must be monotonically increasing or
  936.    SEE ALSO: interp, digitize, span
  937.  */
  938.  
  939. extern sort;
  940. /* DOCUMENT sort(x)
  941.          or sort(x, which)
  942.      returns an array of longs with dimsof(X) containing index values
  943.      such that X(sort(X)) is a monotonically increasing array.  X can
  944.      contain integer, real, or string values.  If X has more than one
  945.      dimension, WHICH determines the dimension to be sorted.  The
  946.      default WHICH is 1, corresponding to the first dimension of X.
  947.      WHICH can be non-positive to count dimensions from the end of X;
  948.      in particular a WHICH of 0 will sort the final dimension of X.
  949.  
  950.      WARNING: The sort function is non-deterministic if some of the
  951.               values of X are equal, because the Quick Sort algorithm
  952.           involves a random selection of a partition element.
  953.  
  954.      For information on sorting with multiple keys (and on making
  955.      sort deterministic), type the following:
  956.         #include "msort.i"
  957.         help, msort
  958.  
  959.    SEE ALSO: median, digitize, interp, integ, histogram
  960.  */
  961.  
  962. func median(x, which)
  963. /* DOCUMENT median(x)
  964.          or median(x, which)
  965.      returns the median of the array X.  The search for the median takes
  966.      place along the dimension of X specified by WHICH.  WHICH defaults
  967.      to 1, meaning the first index of X.  The median function returns an
  968.      array with one fewer dimension than its argument X (the WHICH
  969.      dimension of X is missing in the result), in exact analogy with
  970.      rank reducing index range functions.  If dimsof(X)(WHICH) is
  971.      odd, the result will have the same data type as X; if even, the
  972.      result will be a float or a double, since the median is defined
  973.      as the arithmetic mean between the two central values in that
  974.      case.
  975.    SEE ALSO: sort, built-in index range functions such as avg, rms
  976.  */
  977. {
  978.   if (is_void(which)) which= 1;
  979.   list= sort(x, which);
  980.   dims= dimsof(x);
  981.   if (which<1) which= dims(1)-which;
  982.   n= dims(1+which);
  983.   odd= n%2;
  984.   n/= 2;         /* index with half above, half below... */
  985.   n+= 1;         /* ...corrected for 1-origin */
  986.   stride= 1;
  987.   for (i=1 ; i<which ; i++) stride*= dims(1+i);
  988.   ldims= dims(1)-which+1;
  989.   /**/ local l;
  990.   reshape, l, &list, long, stride, grow(ldims, dims(1+which:));
  991.   lm= l(,n,..);
  992.   if (which<dims(1)) dims(1+which:-1)= dims(2+which:0);
  993.   --dims(1);
  994.   reshape, lm, long, dims;
  995.   xm= x(lm);
  996.   if (!odd) {     /* even length dimensions have more complicated median */
  997.     reshape, lm;  /* undefine the LValue lm so following define works */
  998.     lm= l(,n-1,..);
  999.     reshape, lm, long, dims;
  1000.     xm= 0.5f*(xm+x(lm));
  1001.   }
  1002.   return xm;
  1003. }
  1004.  
  1005. extern transpose;
  1006. /* DOCUMENT transpose(x)
  1007.          or transpose(x, permutation1, permutation2, ...)
  1008.      transpose the first and last dimensions of array X.  In the second
  1009.      form, each PERMUTATION specifies a simple permutation of the
  1010.      dimensions of X.  These permutations are compounded left to right
  1011.      to determine the final permutation to be applied to the dimensions
  1012.      of X.  Each PERMUTATION is either an integer or a 1D array of
  1013.      integers.  A 1D array specifies a cyclic permutation of the
  1014.      dimensions as follows: [3, 5, 2] moves the 3rd dimension to the
  1015.      5th dimension, the 5th dimension to the 2nd dimension, and the 2nd
  1016.      dimension to the 3rd dimension.  Non-positive numbers count from the
  1017.      end of the dimension list of X, so that 0 is the final dimension,
  1018.      -1 in the next to last, etc.  A scalar PERMUTATION is a shorthand
  1019.      for a cyclic permutation of all of the dimensions of X.  The value
  1020.      of the scalar is the dimension to which the 1st dimension will move.
  1021.  
  1022.      Examples:  Let x have dimsof(x) equal [6, 1,2,3,4,5,6] in order
  1023.         to be able to easily identify a dimension by its length. Then:
  1024.     dimsof(x)                          == [6, 1,2,3,4,5,6]
  1025.     dimsof(transpose(x))               == [6, 6,2,3,4,5,1]
  1026.         dimsof(transpose(x,[1,2]))         == [6, 2,1,3,4,5,6]
  1027.     dimsof(transpose(x,[1,0]))         == [6, 6,2,3,4,5,1]
  1028.     dimsof(transpose(x,2))             == [6, 6,1,2,3,4,5]
  1029.     dimsof(transpose(x,0))             == [6, 2,3,4,5,6,1]
  1030.     dimsof(transpose(x,3))             == [6, 5,6,1,2,3,4]
  1031.     dimsof(transpose(x,[4,6,3],[2,5])) == [6, 1,5,6,3,2,4]
  1032.  */
  1033.  
  1034. /*--------------------------------------------------------------------------*/
  1035.  
  1036. extern strlen;
  1037. /* DOCUMENT strlen(string_array)
  1038.      returns an long array with dimsof(STRING_ARRAY) containing the
  1039.      lengths of the strings.  The null string (0) is considered to
  1040.      have length 0, just like "".
  1041.    SEE ALSO: strmatch, strpart, strtok
  1042.  */
  1043.  
  1044. extern strtok;
  1045. /* DOCUMENT strtok(string_array, delimiters)
  1046.          or strtok(string_array)
  1047.      strips the first token off of each string in STRING_ARRAY.
  1048.      A token is delimited by any of the characters in the string
  1049.      DELIMITERS.  If DELIMITERS is blank, nil, or not given, the
  1050.      default DELIMITERS is " \t\n" (blanks, tabs, or newlines).
  1051.      The result is a string array ts with dimensions
  1052.      2-by-dimsof(STRING_ARRAY); ts(1,) is the first token, and
  1053.      ts(2,) is the remainder of the string (the character which
  1054.      terminated the first token will be in neither of these parts).
  1055.      The ts(2,) part will be 0 (i.e.- the null string) if no more
  1056.      characters remain after ts(1,); the ts(1,) part will be 0 if
  1057.      no token was present.  A STRING_ARRAY element may be 0, in
  1058.      which case (0, 0) is returned for that element.
  1059.    SEE ALSO: strmatch, strpart, strlen
  1060.  */
  1061.  
  1062. extern strmatch;
  1063. /* DOCUMENT strmatch(string_array, pattern)
  1064.          or strmatch(string_array, pattern, case_fold)
  1065.      returns an int array with dimsof(STRING_ARRAY) with 0 where
  1066.      PATTERN was not found in STRING_ARRAY and 1 where it was found.
  1067.      If CASE_FOLD is specified and non-0, the pattern match is
  1068.      insensitive to case, that is, an upper case letter will match
  1069.      the same lower case letter and vice-versa.
  1070.    SEE ALSO: strtok, strpart, strlen
  1071.  */
  1072.  
  1073. extern strpart;
  1074. /* DOCUMENT strpart(string_array, m:n)
  1075.       returns another string array with the same dimensions as
  1076.       STRING_ARRAY which consists of characters M through N of
  1077.       the original strings.  M and N are 1-origin indices; if
  1078.       M is omitted, the default is 1; if N is omitted, the default
  1079.       is the end of the string.  If M or N is non-positive, it is
  1080.       interpreted as an index relative to the end of the string,
  1081.       with 0 being the last character, -1 next to last, etc.
  1082.       Finally, the returned string will be shorter than N-M+1
  1083.       characters if the original doesn't have an Mth or Nth
  1084.       character, with "" (note that this is otherwise impossible)
  1085.       if neither an Mth nor an Nth character exists.  A 0
  1086.       is returned for any string which was 0 on input.
  1087.    SEE ALSO: strmatch, strtok, strlen
  1088.  */
  1089.  
  1090. /*--------------------------------------------------------------------------*/
  1091.  
  1092. extern open;
  1093. /* DOCUMENT f= open(filename)
  1094.          or f= open(filename, filemode)
  1095.          or f= open(filename, filemode, errmode)
  1096.      opens the file FILENAME according to FILEMODE (both are strings).
  1097.      If ERRMODE is non-nil and non-zero, fail by returning nil F,
  1098.      otherwise failure to open or create the file is a runtime error.
  1099.  
  1100.      To use ERRMODE to check for the existence of a file:
  1101.         if (open(filename,,1)) file_exists;
  1102.     else file_does_not_exist;
  1103.  
  1104.      The return value F is an IOStream (or just stream for short).  When
  1105.      the last reference to this return value is discarded, the file will
  1106.      be closed.  The file can also be explicitly closed with the close
  1107.      function.  The FILEMODE determines whether the file is to be
  1108.      opened in read, write, or update mode, and whether writes are
  1109.      restricted to the end-of-file (append mode).  FILEMODE also
  1110.      determines whether the file is opened as a text file or as a
  1111.      binary file.  FILEMODE can have the following values, which are
  1112.      the same as for the ANSI standard fopen function:
  1113.         "r"     - read only
  1114.         "w"     - write only, random access, existing file overwritten
  1115.     "a"     - write only, forced to end-of-file,
  1116.             existing file preserved
  1117.     "r+"    - read/write, random access, existing file preserved
  1118.     "w+"    - read/write, random access, existing file overwritten
  1119.     "a+"    - read/write, reads random access,
  1120.             writes forced to end-of-file, existing file preserved
  1121.     "rb"  "wb"  "ab"  "r+b"  "rb+"  "w+b"  "wb+"  "a+b"  "ab+"
  1122.             without b means text file, with b means binary file
  1123.      The default FILEMODE is "r" -- open an existing text file for
  1124.      reading.
  1125.  
  1126.      The read and write functions perform I/O on text files.
  1127.      I/O to binary files may be performed explicitly using the save
  1128.      and restore functions, or implicitly by using the stream variable
  1129.      F as if it were a data structure instance (e.g.- f.x refers to
  1130.      variable x in the binary file f).
  1131.   SEE ALSO: create, close, read, write, rdline, bookmark, backup,
  1132.             rename, remove, save, restore
  1133.  */
  1134.  
  1135. func create(filename)
  1136. /* DOCUMENT f= create(filename)
  1137.      is a synonym for       f= open(filename, "w")
  1138.      Creates a new text file FILENAME, destroying any existing file of
  1139.      that name.  Use the write function to write into the file F.
  1140.    SEE ALSO: write, close, open
  1141.  */
  1142. { return open(filename, "w"); }
  1143.  
  1144. extern close;
  1145. /* DOCUMENT close, f
  1146.      closes the I/O stream F (returned earlier by the open function).
  1147.      If F is a simple variable reference (as opposed to an expression),
  1148.      the close function will set F to nil.  If F is the only reference
  1149.      to the I/O stream, then "close, f" is equivalent to "f= []".
  1150.      Otherwise, "close, f" will close the file (so that subsequent
  1151.      I/O operations will fail) and print a warning message about the
  1152.      outstanding ("stale") references.
  1153.   SEE ALSO: open, read, write, rdline, bookmark, backup, save, restore,
  1154.             rename, remove
  1155.  */
  1156.  
  1157. extern rename;
  1158. extern remove;
  1159. /* DOCUMENT rename, old_filename, new_filename
  1160.             remove filename
  1161.      rename or remove a file.
  1162.    SEE ALSO: open, close, openb, closeb
  1163.  */
  1164.  
  1165. extern read;
  1166. extern sread;
  1167. /* DOCUMENT n= read(f, format=fstring, obj1, obj2, ...)
  1168.          or n= read(prompt= pstring, format=fstring, obj1, obj2, ...)
  1169.      or n= sread(source, format=fstring, obj1, obj2, ...)
  1170.      reads text from I/O stream F (1st form), or from the keyboard (2nd
  1171.      form), or from the string or string array SOURCE (3rd form),
  1172.      interprets it according to the optional FSTRING, and uses that
  1173.      interpretation to assign values to OBJ1, OBJ2, ...  If the input
  1174.      is taken from the keyboard, the optional prompt PSTRING (default
  1175.      "read> ") is printed before each line is read.  The Yorick write
  1176.      function does not interact with the read function -- writes are
  1177.      always to end-of-file, and do not affect the sequence of lines
  1178.      returned by read.  The backup (and bookmark) function is the
  1179.      only way to change the sequence of lines returned by read.
  1180.  
  1181.      There must be one non-supressed conversion specifier (see below)
  1182.      in FSTRING for each OBJ to be read; the type of the conversion
  1183.      specifier must generally match the type of the OBJ.  That is,
  1184.      an integer OBJ requires an integer specifier (d, i, o, u, or x)
  1185.      in FSTRING, a real OBJ requires a real specifier (e, f, or g),
  1186.      and a string OBJ requires a string specifier (s or []).  An OBJ
  1187.      may not be complex, a pointer, a structure instance, or any non-
  1188.      array Yorick object.  If FSTRING is not supplied, or if it has
  1189.      fewer conversion specifiers than the number of OBJ arguments,
  1190.      then Yorick supplies default specifiers ("%ld" for integers,
  1191.      "%lg" for reals, and "%s" for strings).  If FSTRING contains more
  1192.      specifiers than there are OBJ arguments, the part of FSTRING
  1193.      beginning with the first specifier with no OBJ is ignored.
  1194.  
  1195.      The OBJ may be scalar or arrays, but the dimensions of every OBJ
  1196.      must be identical.  If the OBJ are arrays, Yorick behaves as
  1197.      if the read were called in a loop numberof(OBJ1) times, filling
  1198.      one array element of each of the OBJ according to FSTRING on
  1199.      each pass through the loop.  (Note that this behavior includes
  1200.      the case of reading columns of numbers by a single call to read.)
  1201.  
  1202.      The return value N is the total number of scalar assignments
  1203.      which were made as a result of this call.  (If there were 4
  1204.      OBJ arguments, and each was an array with 17 elements, a return
  1205.      value of N==35 would mean the following:  The first 8 elements
  1206.      of OBJ1, OBJ2, OBJ3, and OBJ4 were read, and the 9th element of
  1207.      OBJ1, OBJ2, and OBJ3 was read.)  The read function sets any
  1208.      elements of the OBJ which were not read to zero -- hence,
  1209.      independent of the returned N, the all of the old data in the
  1210.      OBJ arguments is overwritten.
  1211.  
  1212.      The read or sread functions continue reading until either:
  1213.      (1) all elements of all OBJ have been filled, or (2) end-of-file
  1214.      (or end of SOURCE for sread) is reached ("input failure"), or
  1215.      (3) part of FSTRING or a conversion specifier supplied by
  1216.      default fails to match the source text ("matching failure").
  1217.  
  1218.      The FSTRING is composed of a series of "directives" which are
  1219.      (1) whitespace -- means to skip any amount of whitespace in the
  1220.          source text
  1221.      (2) characters other than whitespace and % -- must match the
  1222.          characters in the source text exactly, or matching failure
  1223.      occurs and the read operation stops
  1224.      (3) conversion specifiers beginning with % and ending with a
  1225.          character specifying the type of conversion -- optionally
  1226.      skip whitespace, then convert as many characters as
  1227.      continue to "look like" the conversion type, possibly
  1228.      producing a matching failure
  1229.      The conversion specifier is of the form %*WSC, where:
  1230.      * is either the character '*' or not present
  1231.        A specifier beginning with %* does not correspond to any of
  1232.        the OBJ; the converted value will be discarded.
  1233.      W is either a positive decimal integer specifying the maximum
  1234.        field width (not including any skipped leading whitespace),
  1235.        or not present if any number of characters up to end-of-line
  1236.        is acceptable.
  1237.      S is either one of the characters 'h', 'l', or 'L', or not
  1238.        present.  Yorick allows this for compatibility with the C
  1239.        library functions, but ignores it.
  1240.      C is a character specifying the type of conversion:
  1241.        d   - decimal integer
  1242.        i   - decimal, octal (leading 0), or hex (leading 0x) integer
  1243.        o   - octal integer
  1244.        u   - unsigned decimal integer (same as d for Yorick)
  1245.        x, X            - hex integer
  1246.        e, f, g, E, G   - floating point real
  1247.        s   - string of non-whitespace characters
  1248.        [xxx]   - (xxx is any sequence of characters) longest string
  1249.                  of characters matching those in the list
  1250.        [^xxx]  - longest string of characters NOT matching those in
  1251.                  the list (this is how you can extend %s to be
  1252.          delimited by something other than whitespace)
  1253.        %   - the ordinary % character; complete conversion
  1254.              specification must be "%%"
  1255.  
  1256.      The read function is modeled on the ANSI standard C library
  1257.      fscanf and sscanf functions, but differs in several respects:
  1258.        (1) Yorick's read cannot handle the %c, %p, or %n conversion
  1259.            specifiers in FSTRING.
  1260.        (2) Yorick's read never results in a portion of a line
  1261.            being read -- any unused part of a line is simply discarded
  1262.        (end FSTRING with "%[^\n]" if you want to save the trailing
  1263.        part of an input line).
  1264.        (3) As a side effect of (2), there are some differences between
  1265.            fscanf and Yorick's read in how whitespace extending across
  1266.        newlines is handled.
  1267.    SEE ALSO: rdline, write, open, close, bookmark, backup, save, restore,
  1268.              read_n
  1269.  */
  1270.  
  1271. extern rdline;
  1272. /* DOCUMENT rdline(f)
  1273.          or rdline(f, n, prompt= pstring)
  1274.      returns next line from stream F (stdin if F nil).  If N is non-nil,
  1275.      returns a string array containing the next N lines of F.  If
  1276.      end-of-file occurs, rdline returns nil strings.  If F is nil,
  1277.      uses the PSTRING to prompt for input (default "read> ").
  1278.    SEE ALSO: read, open, close, bookmark, backup, read_n
  1279.  */
  1280.  
  1281. func read_n(f, &n0, &n1, &n2, &n3, &n4, &n5, &n6, &n7, &n8, &n9)
  1282. /* DOCUMENT read_n, f, n0, n1, n2, ...
  1283.      grabs the next numbers N0, N1, N2, ... from file F, skipping over
  1284.      any whitespace, comma, semicolon, or colon delimited tokens which
  1285.      are not numbers.  (Actually, only the first and last characters of
  1286.      the token have to look like a number -- 4xxx3 would be read as 4.)
  1287.      ***WARNING*** at most ten Ns are allowed
  1288.      The Ns can be arrays, provided all have the same dimensions.
  1289.    SEE ALSO: read, rdline
  1290.  */
  1291. {
  1292.   require, "readn.i";
  1293.   return raw_read_n(f, n0, n1, n2, n3, n4, n5, n6, n7, n8, n9);
  1294. }
  1295.  
  1296. extern write;
  1297. extern swrite;
  1298. /* DOCUMENT n= write(f, format=fstring, linesize=l, obj1, obj2, ...)
  1299.             n= write(format=fstring, linesize=l, obj1, obj2, ...)
  1300.      or strings= swrite(format=fstring, linesize=l, obj1, obj2, ...)
  1301.      writes text to I/O stream F (1st form), or to the terminal (2nd
  1302.      form), or to the STRINGS string array (3rd form), representing
  1303.      arrays OBJ1, OBJ2, ..., according to the optional FSTRING.  The
  1304.      optional linesize L defaults to 80 characters, and helps restrict
  1305.      line lengths when FSTRING is not given, or does not contain
  1306.      newline directives.  The write function always appends to the
  1307.      end of a text file; the position for a sequence of reads is
  1308.      not affected by intervening writes.
  1309.  
  1310.      There must be one conversion specifier (see below) in FSTRING for
  1311.      each OBJ to be written; the type of the conversion specifier must
  1312.      generally match the type of the OBJ.  That is, an integer OBJ
  1313.      requires an integer specifier (d, i, o, u, x, or c) in FSTRING,
  1314.      a real OBJ requires a real specifier (e, f, or g), a string OBJ
  1315.      requires the string specifier (s), and a pointer OBJ requires a
  1316.      the pointer specifier (p).  An OBJ may not be complex, a structure
  1317.      instance, or any non-array Yorick object.  If FSTRING is not
  1318.      supplied, or if it has fewer conversion specifiers than the
  1319.      number of OBJ arguments, then Yorick supplies default specifiers
  1320.      (" %8ld" for integers, " %14.6lg" for reals, " %s" for strings, and
  1321.      " %8p" for pointers).  If FSTRING contains more specifiers than
  1322.      there are OBJ arguments, the part of FSTRING beginning with the
  1323.      first specifier with no OBJ is ignored.
  1324.  
  1325.      The OBJ may be scalar or arrays, but the dimensions of the OBJ
  1326.      must be conformable.  If the OBJ are arrays, Yorick behaves as
  1327.      if he write were called in a loop dimsof(OBJ1, OBJ2, ...) times,
  1328.      writing one array element of each of the OBJ according to FSTRING
  1329.      on each pass through the loop.  The swrite function returns a
  1330.      string array with dimensions dimsof(OBJ1, OBJ2, ...).  The write
  1331.      function inserts a newline between passes through the array if
  1332.      the line produced by the previous pass did not end with a
  1333.      newline, and if the total number of characters output since the
  1334.      previous inserted newline, plus the number of characters about
  1335.      to be written on the current pass, would exceed L characters
  1336.      (L defaults to 80).  The write function returns the total
  1337.      number of characters output.
  1338.  
  1339.      The FSTRING is composed of a series of "directives" which are
  1340.      (1) characters other than % -- copied directly to output
  1341.      (2) conversion specifiers beginning with % and ending with a
  1342.          character specifying the type of conversion -- specify
  1343.      how to convert an OBJ into characters for output
  1344.      The conversion specifier is of the form %FW.PSC, where:
  1345.      F is zero or more optional flags:
  1346.        - left justify in field width
  1347.        + signed conversion will begin with either + or -
  1348.          (space) signed conversion  will begin with either space or -
  1349.        # alternate form (see description of each type below)
  1350.        0 pad field width with leading 0s instead of leading spaces
  1351.      W is either a decimal integer specifying the minimum field width
  1352.        (padded as specified by flags), or not present to use the
  1353.        minimum number of characters required.
  1354.      .P is either a decimal integer specifying the precision of the
  1355.        result, or not present to get the default.  For integers, this
  1356.        is the number of digits to be printed (possibly forcing leading
  1357.        zeroes), and defaults to 1.  For reals, this is the number of
  1358.        digits after the decimal point, and defaults to 6.  For strings,
  1359.        this is the maximum number of characters to print, and defaults
  1360.        to infinity.
  1361.      S is either one of the characters 'h', 'l', or 'L', or not
  1362.        present.  Yorick allows this for compatibility with the C
  1363.        library functions, but ignores it.
  1364.      C is a character specifying the type of conversion:
  1365.        d, i  - decimal integer
  1366.        o     - octal integer (# forces leading 0)
  1367.        u     - unsigned decimal integer (same as d for Yorick)
  1368.        x, X            - hex integer (# forces leading 0x)
  1369.        f     - floating point real in fixed point notation
  1370.                (# forces decimal)
  1371.        e, E  - floating point real in scientific notation
  1372.        g, G  - floating point real in fixed or scientific notation
  1373.                depending on the value converted (# forces decimal)
  1374.        s   - string of ASCII characters
  1375.        c   - integer printed as corresponding ASCII character
  1376.        p   - pointer
  1377.        %   - the ordinary % character; complete conversion
  1378.              specification must be "%%"
  1379.  
  1380.      The write function is modeled on the ANSI standard C library
  1381.      fprintf and sprintf functions, but differs in several respects:
  1382.        (1) Yorick's write cannot handle the %n conversion specifier
  1383.            in FSTRING.
  1384.        (2) Yorick's write may insert additional newlines if the OBJ
  1385.            are arrays, to avoid extremely long output lines.
  1386.    SEE ALSO: print, exit, error, read, rdline, open, close, save, restore
  1387.  */
  1388.  
  1389. extern bookmark;
  1390. extern backup;
  1391. /* DOCUMENT backup, f
  1392.          or bmark= bookmark(f)
  1393.             ...
  1394.             backup, f, bmark
  1395.      back up the text stream F, so that the next call to the read
  1396.      function returns the same line as the previous call to read
  1397.      (note that you can only back up one line).  If the optional
  1398.      second argument BMARK is supplied, restores the state of the
  1399.      file F to its state at the time the bookmark function was
  1400.      called.
  1401.      After a matching failure in read, use the single argument form
  1402.      of backup to reread the line containing the matching failure.
  1403.    SEE ALSO: read, rdline, open, close
  1404.  */
  1405.  
  1406. extern include;
  1407. extern require;
  1408. /* DOCUMENT #include "yorick_source.i"
  1409.             require, filename
  1410.             include, filename
  1411.          or include, filename, now
  1412.  
  1413.      #include is a parser directive, not a Yorick statement.  Use it
  1414.      to read Yorick source code which you have saved in a file; the
  1415.      file yorick_source.i will be read one line at a time, exactly as
  1416.      if you had typed those lines at the keyboard.  The following
  1417.      directories are searched (in this order) to find yorick_source.i:
  1418.  
  1419.         .               (current working directory)
  1420.     ~/Yorick        (your personal directory of Yorick functions)
  1421.     Y_SITE/include  (Yorick distribution library)
  1422.     Y_SITE/contrib  (contributed source at your site)
  1423.  
  1424.      To find out what is available in the Yorick/include directory,
  1425.      type:
  1426.          library
  1427.      You can also type
  1428.          Y_SITE
  1429.      to find the name of the site directory at your site, go to the
  1430.      include or contrib subdirectory, and browse through the *.i files.
  1431.      This is a good way to learn how to write a Yorick program.  Be
  1432.      alert for files like README as well.
  1433.  
  1434.      The require function checks to see whether FILENAME has already
  1435.      been included (actually whether any file with the same final
  1436.      path component has been included).  If so, require is a no-op,
  1437.      otherwise, the action is the same as the include function with
  1438.      NOW == 1.
  1439.  
  1440.      The include function causes Yorick to parse and execute FILENAME
  1441.      immediately.  The effect is similar to the #include parser
  1442.      directive, except the finding, parsing, and execution of FILENAME
  1443.      occurs at runtime.  If the NOW argument is given and positive,
  1444.      the include occurs immediately, if nil or 0, it occurs just before
  1445.      the next line would have been parsed.  If NOW is negative, the
  1446.      include file is pushed onto a stack, and will be popped off and
  1447.      parsed when all pending input has been processed.
  1448.  
  1449.      Unless you are writing a startup file, or have some truly bizarre
  1450.      technical reason for using the include function, use #include
  1451.      instead.  The functional form of include may involve recursive
  1452.      parsing, which you will not be able to understand without deep
  1453.      study.  Stick with #include.
  1454.  
  1455.    SEE ALSO: set_path, Y_SITE
  1456.  */
  1457.  
  1458. func library(void)
  1459. /* DOCUMENT library
  1460.      print the Y_SITE/include/README file at the terminal.
  1461.  */
  1462. {
  1463.   f= open(Y_SITE+"include/README");
  1464.   while ((line= rdline(f))) write, line;
  1465. }
  1466.  
  1467. /*--------------------------------------------------------------------------*/
  1468.  
  1469. extern cd;
  1470. /* DOCUMENT cd, directory_name
  1471.          or cd(directory_name)
  1472.      change current working directory to DIRECTORY_NAME, returning
  1473.      the expanded path name (i.e.- with leading environment variables,
  1474.      ., .., or ~ replaced by the actual pathname).  If called as a
  1475.      function, returns nil to indicate failure, otherwise failure
  1476.      causes a Yorick error.
  1477.    SEE ALSO: get_cwd, get_home, get_env, get_argv
  1478.  */
  1479.  
  1480. extern get_cwd;
  1481. extern get_home;
  1482. /* DOCUMENT get_cwd()
  1483.          or get_home()
  1484.      returns the pathname of the current working directory or of your
  1485.      home directory.
  1486.    SEE ALSO: cd, get_env, get_argv
  1487.  */
  1488.  
  1489. extern get_env;
  1490. /* DOCUMENT get_env(environment_variable_name)
  1491.      returns the environment variable (a string) associated with
  1492.      ENVIRONMENT_VARIABLE_NAME (calls ANSI getenv routine).
  1493.    SEE ALSO: cd, get_cwd, get_home, get_env, get_argv
  1494.  */
  1495.  
  1496. extern get_argv;
  1497. /* DOCUMENT get_argv()
  1498.      returns string array containing the argv from the command line.
  1499.      The -batch and batch_include.i arguments are removed (not returned).
  1500.    SEE ALSO: process_argv, cd, get_cwd, get_home, get_env, batch
  1501.  */
  1502.  
  1503. func process_argv(msg)
  1504. /* DOCUMENT remaining= process_argv()
  1505.        -or- remaining= process_argv("your startup message")
  1506.      Performs standard command line processing.  This function is
  1507.      invoked by the default custom.i file (in $Y_HOME/include); you
  1508.      can also invoke it from your personal ~/Yorick/custom.i file.
  1509.      The process_argv calls get_argv, removes any arguments of
  1510.      the form "-ifilename" or "-i filename" (the latter is a pair of
  1511.      arguments.  It returns any arguments not of this form as its
  1512.      result, after including any filenames it found in the order
  1513.      they appeared on the command line.
  1514.      The optional string argument may be an array of strings to print
  1515.      a multi-line message.
  1516.  
  1517.    SEE ALSO: batch
  1518.  */
  1519. {
  1520.   command_line= get_argv();
  1521.   if (numberof(command_line)>=2) {
  1522.     command_line= command_line(2:);
  1523.     mask= strmatch(strpart(command_line, 1:2), "-i");
  1524.     list= where(mask);
  1525.     n= numberof(list);
  1526.     for (i=1 ; i<=n ; i++) {
  1527.       file= strpart(command_line(list(i)), 3:);
  1528.       if (file=="") {
  1529.     if (list(i)==numberof(command_line)) break;  /* ignore trailing -i */
  1530.     file= command_line(list(i)+1);
  1531.     mask(list(i)+1)= 1;
  1532.       }
  1533.       include, file;
  1534.     }
  1535.     command_line= command_line(where(!mask));
  1536.   } else {
  1537.     command_line= [];
  1538.   }
  1539.   if (numberof(command_line)<1 || noneof(command_line=="-q")) {
  1540.     if (is_void(msg)) {
  1541.       if(is_void(is_a_mac)) {
  1542.         msg= [
  1543. " Copyright (c) 1994.  The Regents of the University of California.",
  1544. " All rights reserved.  Yorick 1.1 ready.  For help type 'help'"];
  1545.         write, msg, format="%s\n";
  1546.       } else {
  1547.         val= is_a_mac();
  1548.         if(val == 1) {
  1549.           msg= [
  1550. " Copyright (c) 1994.  The Regents of the University of California.",
  1551. " Yorick for 68K Macintosh without FPU, release 1.1vr1.",
  1552. " All rights reserved.  Yorick 1.1 ready.  For help type 'help'"];
  1553.           write, msg, format="%s\n";
  1554.         } else if(val == 2) {
  1555.           msg= [
  1556. " Copyright (c) 1994.  The Regents of the University of California.",
  1557. " Yorick for 68K Macintosh with FPU, release 1.1vr1.",
  1558. " All rights reserved.  Yorick 1.1 ready.  For help type 'help'"];
  1559.           write, msg, format="%s\n";
  1560.         } else {
  1561.           msg= [
  1562. " Copyright (c) 1994.  The Regents of the University of California.",
  1563. " Yorick for Power Macintosh, release 1.1vr1.",
  1564. " All rights reserved.  Yorick 1.1 ready.  For help type 'help'"];
  1565.           write, msg, format="%s\n";
  1566.         }
  1567.       }
  1568.     }
  1569.     return command_line;
  1570.   } else {
  1571.     return command_line(where(command_line!="-q"));
  1572.   }
  1573. }
  1574.  
  1575. /*--------------------------------------------------------------------------*/
  1576.  
  1577. func openb(filename, clogfile, update, open102=)
  1578. /* DOCUMENT file= openb(filename)
  1579.          or file= openb(filename, clogfile)
  1580.      open the existing file FILENAME for read-only binary I/O.
  1581.      (Use updateb or createb, respectively, to open an existing file
  1582.       with read-write access or to create a new file.)
  1583.      If the CLOGFILE argument is supplied, it represents the structure
  1584.      of FILENAME in the Clog binary data description language.
  1585.      After an openb, the file variable may be used to extract variables
  1586.      from the file as if it were a structure instance.  That is, the
  1587.      expression "file.var" refers to the variable "var" in file "file".
  1588.      A complete list of the variable names present in the file may
  1589.      be obtained using the get_vars function.  If the file contains
  1590.      history records, the jt and jc functions may be used to set the
  1591.      current record -- initially, the first record is current.
  1592.      The restore function may be used to make memory copies of data
  1593.      in the file; this will be faster than a large number of
  1594.      references to "file.var".
  1595.    SEE ALSO: updateb, createb, open, cd
  1596.              show, jt, jc, restore
  1597.              get_vars, get_times, get_ncycs, get_member, has_records
  1598.              set_blocksize, dump_clog, read_clog, recover_file
  1599.          openb_hooks, open102, close102, get_addrs
  1600.  */
  1601. {
  1602.   f= open(filename, (update? "r+b" : "rb"));
  1603.   if (!is_void(clogfile)) return read_clog(f, clogfile);
  1604.   if (!is_void(open102)) yPDBopen= ((open102&3)|(at_pdb_open&~3));
  1605.   else yPDBopen= at_pdb_open;
  1606.   for (i=1 ; i<=numberof(openb_hooks) ; i++) {
  1607.     if (symbol_def(openb_hooks(i))(f)) continue;
  1608.     if (has_records(f)) edit_times, f;  /* force increasing times */
  1609.     return f;
  1610.   }
  1611.   return [];
  1612. }
  1613.  
  1614. local openb_hooks;
  1615. /* DOCUMENT openb_hooks
  1616.      array of names of functions to be tried by openb if the file to be
  1617.      opened is not a PDB file.  By default,
  1618.        openb_hooks= ["_not_pdbf", "_not_cdf"].
  1619.      The hook functions will be called with the file as argument
  1620.      (e.g.- _not_cdf(file)), beginning with openb_hooks(1), until
  1621.      one of them returns 0.  Note that a hook should return 0 if it
  1622.      "recognizes" the file as one that it should be able to open, but
  1623.      finds that the file is misformatted (alternatively, it could call
  1624.      error to abort the whole process).
  1625.  */
  1626. openb_hooks= ["_not_pdbf", "_not_cdf"];
  1627.  
  1628. func show(f, pat)
  1629. /* DOCUMENT show, f
  1630.          or show, f, pat
  1631.          or show, f, 1
  1632.      prints a summary of the variables contained in binary file F.
  1633.      If there are too many variables, use the second form to select
  1634.      only those variables whose first few characters match PAT.
  1635.      In the third form, continues the previous show command where it
  1636.      left off -- this may be necessary for files with large numbers of
  1637.      variables.
  1638.      The variables are printed in alphabetical order down the columns.
  1639.      The print function can be used to obtain other information about F.
  1640.    SEE ALSO: openb, jt, jc
  1641.  */
  1642. {
  1643.   require, "show.i";
  1644.   raw_show, f, pat;
  1645. }
  1646.  
  1647. func collect(f, name)
  1648. /* DOCUMENT result= collect(f, name_string)
  1649.      scans through all records of the history file F accumulating the
  1650.      variable NAME_STRING into a single array with one additional
  1651.      index varying from 1 to the number of records.
  1652.  
  1653.      NAME_STRING can be either a simple variable name, or a name
  1654.      followed by up to four simple indices which are either nil, an
  1655.      integer, or an index range with constant limits.  (Note that
  1656.      0 or negative indices count from the end of a dimension.)
  1657.  
  1658.      Examples:
  1659.         collect(f, "xle")        -- collects the variable f.xle
  1660.     collect(f, "tr(2,2:)")   -- collects f.tr(2,2:)
  1661.     collect(f, "akap(2,-1:0,)") -- collects f.akap(2,-1:0,)
  1662.                  (i.e.- akap in the last two values of its
  1663.                     second index)
  1664.  
  1665.    SEE ALSO: get_times
  1666.  */
  1667. {
  1668.   require, "collec.i";
  1669.   return raw_collect(f, name);
  1670. }
  1671.  
  1672. extern get_member;
  1673. /* DOCUMENT get_member(f_or_s, member_name)
  1674.      returns F_OR_S member MEMBER_NAME, like F_OR_S.MEMBER_NAME syntax,
  1675.      but MEMBER_NAME can be a computed string.  The F_OR_S may be a
  1676.      binary file or a structure instance.
  1677.    SEE ALSO: openb
  1678.  */
  1679.  
  1680. extern read_clog;
  1681. /* DOCUMENT file= read_clog(file, clog_name)
  1682.      raw routine to set the binary data structure of FILE according
  1683.      to the text description in the Contents Log file CLOG_NAME.
  1684.  */
  1685.  
  1686. func recover_file(filename, clogfile)
  1687. /* DOCUMENT recover_file, filename
  1688.          or recover_file, filename, clogfile
  1689.      writes the descriptive information at the end of a corrupted
  1690.      binary file FILENAME from its Contents Log file CLOGFILE, which
  1691.      is FILENAME+"L" by default.
  1692.  */
  1693. {
  1694.   if (is_void(clogfile)) clogfile= filename+"L";
  1695.   if (clogfile==filename+"L") {  /* open clobbers this one */
  1696.     changed= 1;
  1697.     rename, clogfile, filename+"M";
  1698.     clogfile= filename+"M";
  1699.   } else {
  1700.     changed= 0;
  1701.   }
  1702.   f= open(filename, "r+b");
  1703.   i= array(char, 12);
  1704.   _read, f, 0, i;
  1705.   read_clog, f, clogfile;
  1706.   if (string(&i)=="!<<PDB:II>>!") _set_pdb, f, at_pdb_close;
  1707.   else _init_clog, f;
  1708.   close, f;
  1709.   if (changed) remove, clogfile;
  1710. }
  1711.  
  1712. extern _not_pdb;
  1713. /* DOCUMENT _not_pdb(file, familyOK)
  1714.      returns 1 if FILE is not a PDB file, otherwise returns 0 after
  1715.      setting the structure and data tables, and cataloguing any
  1716.      history records.  Used to open an existing file.  Also detects
  1717.      a file with an appended Clog description.
  1718.      Before calling _not_pdb, set the variable yPDBopen to the value
  1719.      of at_pdb_open you want to be in force.  (For historical reasons
  1720.      -- in order to allow for the open102 keyword to openb -- _not_pdb
  1721.      looks at the value of the variable yPDBopen, rather than at_pdb_open
  1722.      directly.)
  1723.  */
  1724.  
  1725. local close102, open102, close102_default;
  1726. /* DOCUMENT close102  is a keyword for createb or updateb,
  1727.             open102   is a keyword for openb or updateb
  1728.         close102_default   is a global variable (initially 0)
  1729.           ***Do not use close102_default -- use at_pdb_close
  1730.              -- this is for backward compatibility only***
  1731.  
  1732.         close102=1  means to close the PDB file "Major-Order:102"
  1733.         close102=0  means close it "Major-Order:101"
  1734.            if not specified, uses 1 if close102_default non-zero,
  1735.            otherwise the value specified in at_pdb_close
  1736.  
  1737.         open102=1   means to ignore what the PDB file says internally,
  1738.                     and open it as if it were "Major-Order:102"
  1739.         open102=0   (the default) means to assume the PDB file is
  1740.                         correctly writen
  1741.         open102=2   means to assume that the file is incorrectly
  1742.                     written, whichever way it is marked
  1743.         open102=3   means to ignore what the PDB file says internally,
  1744.                     and open it as if it were "Major-Order:101"
  1745.  
  1746.      The PDB file format comes in two styles, "Major-Order:101", and
  1747.      "Major-Order:102".  Yorick interprets these correctly by default,
  1748.      but other codes may ignore them, or write them incorrectly.
  1749.  
  1750.      Unlike Yorick, not all codes are able to correctly read both
  1751.      styles.  If you are writing a file which needs to be read by
  1752.      a "102 style" code, create it with the close102=1 keyword.
  1753.  
  1754.      If you notice that a file you though was a history file isn't, or
  1755.      that the dimensions of multi-dimensional variables are transposed
  1756.      from the order you expected, the code which wrote the file probably
  1757.      blew it.  Try openb("filename", open102=2).  The choices 1 and 3
  1758.      are for cases in which you know the writing code was supposed to
  1759.      write the file one way or the other, and you don't want to be
  1760.      bothered.
  1761.  
  1762.      The open102 and close102 keywords, if present, override the
  1763.      defaults in the variables at_pdb_open and at_pdb_close.
  1764.  
  1765.    SEE ALSO: at_pdb_open, at_pdb_close
  1766.  */
  1767. close102_default= [];
  1768.  
  1769. local at_pdb_open, at_pdb_close;
  1770. /* DOCUMENT at_pdb_open
  1771.             at_pdb_close
  1772.      bits for optional behavior when a PDB file is opened or closed:
  1773.  
  1774.      at_pdb_open:
  1775.      000  Major-Order:  value specified in file is correct
  1776.      001  Major-Order:102 always 
  1777.      002  Major-Order:  opposite from what file says
  1778.      003  Major-Order:101 always
  1779.  
  1780.      004  Strip Basis @... suffices from variable names (when possible)
  1781.           Danger!  If you do this and open a file for update, the variable
  1782.       names will be stripped when you close the file!
  1783.      010  Use Basis @history convention on input
  1784.  
  1785.      The 001 and 002 bits may be overridden by the open102 keyword.
  1786.      The default value of at_pdb_open is 010.
  1787.  
  1788.      at_pdb_close (the value at the time the file is opened or created
  1789.                    is remembered):
  1790.      001  Write Major-Order 102 PDB file
  1791.      002  Write PDB style history data
  1792.         The following are no-ops unless bit 002 is set:
  1793.      004  Use Basis @history convention on output
  1794.      010  Do NOT pack all history record variables into
  1795.           a single structure instance.
  1796.  
  1797.      The 001 bit may be overridden by the close102 keyword or if
  1798.      close102_default is non-zero.
  1799.      The default value of at_pdb_close is 007.
  1800.  
  1801.    SEE ALSO: close102_default
  1802.  */
  1803. at_pdb_open= 010;
  1804. at_pdb_close= 007;
  1805.  
  1806. func _not_pdbf(f) { return _not_pdb(f, 1); }
  1807.  
  1808. extern _init_pdb;
  1809. extern _set_pdb;
  1810. /* DOCUMENT _init_pdb, file, at_pdb_close
  1811.             _set_pdb, file, at_pdb_close
  1812.      initializes a PDB binary file.  Used after creating a new file --
  1813.      must be called AFTER the primitive data formats have been set.
  1814.      The _set_pdb call only sets the CloseHook, on the assumption that
  1815.      the file header has already been written (as in recover_file).
  1816.    SEE ALSO: createb, recover_file, at_pdb_close
  1817.  */
  1818.  
  1819. extern _init_clog;
  1820. /* DOCUMENT _init_clog, file
  1821.      initializes a Clog binary file.  Used after creating a new file --
  1822.      must be called AFTER the primitive data formats have been set.
  1823.  */
  1824.  
  1825. extern dump_clog;
  1826. /* DOCUMENT dump_clog, file, clog_name
  1827.      dumps a Contents Log of the binary file FILE into the text file
  1828.      CLOG_NAME.  Any previous file named CLOG_NAME is overwritten.
  1829.   SEE ALSO: openb
  1830.  */
  1831.  
  1832. func _not_cdf(file)
  1833. /* DOCUMENT _not_cdf(file)
  1834.      is like _not_pdb, but for netCDF files.
  1835.  */
  1836. {
  1837.   i= array(char, 4);
  1838.   _read, f, 0, i;
  1839.   if (string(&i)!="CDF\001") return 1;  /* test magic number */
  1840.   require, "netcdf.i";
  1841.   return raw_not_cdf(file);
  1842. }
  1843.  
  1844. func createb(filename, primitives, close102=)
  1845. /* DOCUMENT file= createb(filename)
  1846.          or file= createb(filename, primitives)
  1847.      creates FILENAME as a PDB file in "w+b" mode, destroying any
  1848.      existing file by that name.  If the PRIMITIVES argument is
  1849.      supplied, it must be the name of a procedure that sets the
  1850.      primitive data types for the file.  The default is to create
  1851.      a file with the native primitive types of the machine on which
  1852.      Yorick is running.  The following PRIMITIVES functions are
  1853.      predefined:
  1854.         sun_primitives    -- appropriate for Sun, HP, IBM, and
  1855.                          most other workstations
  1856.         sun3_primitives   -- appropriate for old Sun-2 or Sun-3
  1857.         dec_primitives    -- appropriate for DEC workstations
  1858.         cray_primitives   -- appropriate for Cray 1, XMP, and YMP
  1859.     mac_primitives    -- appropriate for MacIntosh
  1860.     macl_primitives   -- appropriate for MacIntosh, 12-byte double
  1861.     pc_primitives     -- appropriate for IBM PC
  1862.         vax_primitives    -- appropriate for VAXen only (H doubles)
  1863.         vaxg_primitives   -- appropriate for VAXen only (G doubles)
  1864.         xdr_primitives    -- appropriate for XDR files
  1865.   SEE ALSO: openb, updateb, cd
  1866.             save, add_record, set_filesize, set_blocksize
  1867.         close102, close102_default, at_pdb_open, at_pdb_close
  1868.  */
  1869. {
  1870.   file= open(filename, "w+b");
  1871.   if (!is_void(primitives)) primitives, file;
  1872.   if (!is_void(close102)) yPDBclose= ((close102&1)|(at_pdb_close&~1));
  1873.   else if (is_void(close102_default)) yPDBclose= at_pdb_close;
  1874.   else yPDBclose= ((close102_default&1)|(at_pdb_close&~1));
  1875.   _init_pdb, file, yPDBclose;
  1876.   return file;
  1877. }
  1878.  
  1879. func sun_primitives(file)
  1880. /* DOCUMENT sun_primitives, file
  1881.      sets FILE primitive data types to be native to Sun, HP, IBM, etc.
  1882.  */
  1883. {
  1884.   require, "prmtyp.i";
  1885.   raw_sun_p, file;
  1886. }
  1887.  
  1888. func sun3_primitives(file)
  1889. /* DOCUMENT sun3_primitives, file
  1890.      sets FILE primitive data types to be native to Sun-2 or Sun-3.
  1891.  */
  1892. {
  1893.   require, "prmtyp.i";
  1894.   raw_sun3_p, file;
  1895. }
  1896.  
  1897. func dec_primitives(file)
  1898. /* DOCUMENT dec_primitives, file
  1899.      sets FILE primitive data types to be native to DEC workstations.
  1900.  */
  1901. {
  1902.   require, "prmtyp.i";
  1903.   raw_dec_p, file;
  1904. }
  1905.  
  1906. func cray_primitives(file)
  1907. /* DOCUMENT cray_primitives, file
  1908.      sets FILE primitive data types to be native to Cray 1, XMP, and YMP.
  1909.  */
  1910. {
  1911.   require, "prmtyp.i";
  1912.   raw_cray_p, file;
  1913. }
  1914.  
  1915. func mac_primitives(file)
  1916. /* DOCUMENT mac_primitives, file
  1917.      sets FILE primitive data types to be native to MacIntosh, 8 byte double.
  1918.  */
  1919. {
  1920.   require, "prmtyp.i";
  1921.   raw_mac_p, file;
  1922. }
  1923.  
  1924. func macl_primitives(file)
  1925. /* DOCUMENT macl_primitives, file
  1926.      sets FILE primitive data types to be native to MacIntosh, long double.
  1927.  */
  1928. {
  1929.   require, "prmtyp.i";
  1930.   raw_macl_p, file;
  1931. }
  1932.  
  1933. func pc_primitives(file)
  1934. /* DOCUMENT pc_primitives, file
  1935.      sets FILE primitive data types to be native to IBM PC.
  1936.  */
  1937. {
  1938.   require, "prmtyp.i";
  1939.   raw_pc_p, file;
  1940. }
  1941.  
  1942. func vax_primitives(file)
  1943. /* DOCUMENT vax_primitives, file
  1944.      sets FILE primitive data types to be native to VAXen, H-double, only.
  1945.  */
  1946. {
  1947.   require, "prmtyp.i";
  1948.   raw_vax_p, file;
  1949. }
  1950.  
  1951. func vaxg_primitives(file)
  1952. /* DOCUMENT vaxg_primitives, file
  1953.      sets FILE primitive data types to be native to VAXen, G-double, only.
  1954.  */
  1955. {
  1956.   require, "prmtyp.i";
  1957.   raw_vaxg_p, file;
  1958. }
  1959.  
  1960. func xdr_primitives(file)
  1961. /* DOCUMENT xdr_primitives, file
  1962.      sets FILE primitive data types to be XDR (external data representation).
  1963.  */
  1964. {
  1965.   require, "prmtyp.i";
  1966.   raw_xdr_p, file;
  1967. }
  1968.  
  1969. func updateb(filename, primitives, close102=, open102=)
  1970. /* DOCUMENT file= updateb(filename)
  1971.          or file= updateb(filename, primitives)
  1972.      open a binary date file FILENAME for update (mode "r+b").
  1973.      The optional PRIMITIVES argument is as for the createb function.
  1974.      If the file exists, it is opened as if by openb(filename),
  1975.      otherwise a new PDB file is created as if by createb(filename).
  1976.    SEE ALSO: openb, createb, cd, save, restore, get_vars, get_addrs
  1977.              close102, close102_default, open102, at_pdb_open, at_pdb_close
  1978.  */
  1979. {
  1980.   if (is_void(open(filename, "r", 1)))   /* "rb" does much more work */
  1981.     return createb(filename, primitives, close102=close102);
  1982.   else
  1983.     return openb(filename,,1, open102=open102);
  1984. }
  1985.  
  1986. extern save;
  1987. extern restore;
  1988. /* DOCUMENT save, file, var1, var2, ...
  1989.             restore, file, var1, var2, ...
  1990.      saves the variables VAR1, VAR2, etc. in the binary file FILE,
  1991.      or restores them from that file.
  1992.      The VARi may be either non-record or record data in the case that
  1993.      FILE contains records.
  1994.  
  1995.      If one of the VARi does not already exist in FILE, it is created
  1996.      by the save command; after add_record, save adds or stores VARi to
  1997.      the current record.  See add_record for more.  The VARi may be
  1998.      structure definitions (for the save command) to declare data
  1999.      structures for the file.  This is necessary only in the case that
  2000.      a record variable is a pointer -- all of the potential data types
  2001.      of pointees must be known.  No data structures may be declared
  2002.      using the save command after the first record has been added.
  2003.  
  2004.      If no VARi are present, save saves all array variables, and
  2005.      restore restores every non-record variable in the file if there
  2006.      is no current record, and every variable in the current record if
  2007.      there is one.
  2008.    SEE ALSO: openb, createb, updateb, get_vars, add_record, get_addrs
  2009.              jt, jc, _read, _write, data_align
  2010.  */
  2011.  
  2012. func jt(file, time)
  2013. /* DOCUMENT jt, time
  2014.          or jt, file, time
  2015.          or jt, file
  2016.          or jt, file, -
  2017.      jump to the record nearest the specified TIME.  If no FILE is
  2018.      specified, the current record of all open binary files containing
  2019.      records is shifted.
  2020.      If both FILE and TIME are specified and jt is called as a function,
  2021.      it returns the actual time of the new current record.
  2022.  
  2023.    N.B.: "jt, file" and "jt, file, -" are obsolete.  Use the jr function to
  2024.      step through a file one record at a time.
  2025.  
  2026.      If only the FILE is specified, increment the current record of that
  2027.      FILE by one.  If the TIME argument is - (the pseudo-index range
  2028.      function), decrement the current record of FILE by one.
  2029.      If the current record is the last, "jt, file" unsets the current record
  2030.      so that record variables will be inaccessible until another jt or jc.
  2031.      The same thing happens with "jt, file, -" if the current record was the
  2032.      first.
  2033.      If only FILE is specified, jt returns 1 if there is a new current
  2034.      record, 0 if the call resulted in no current record.  Thus "jt(file)"
  2035.      and "jt(file,-)" may be used as the condition in a while loop to step
  2036.      through every record in a file:
  2037.         file= openb("example.pdb");
  2038.         do {
  2039.       restore, file, interesting_record_variables;
  2040.       ...calculations...
  2041.     } while (jt(file));
  2042.  
  2043.    SEE ALSO: jc, _jt, edit_times, show, jr
  2044.  */
  2045. {
  2046.   return is_void(time)? _jt(file) : _jt(file, time);
  2047. }
  2048.  
  2049. func jc(file, ncyc)
  2050. /* DOCUMENT jc, file, ncyc
  2051.      jump to the record of FILE nearest the specified NCYC.
  2052.    SEE ALSO: jt, _jc, edit_times, show, jr
  2053.  */
  2054. {
  2055.   return _jc(file, ncyc);
  2056. }
  2057.  
  2058. extern _jr;
  2059. extern _jt;
  2060. extern _jc;
  2061. /* DOCUMENT _jt, file, time
  2062.             _jc, file, ncyc
  2063.         _jr, file
  2064.      are raw versions of jt and jc provided to simplify redefining
  2065.      the default jt and jc functions to add additional features.
  2066.      For example, you could redefine jt to jump to a time, then
  2067.      plot something.  The new jt can pass its arguments along to
  2068.      _jt, then call the appropriate plotting functions.
  2069.      There is a raw version of jr as well.
  2070.  */
  2071.  
  2072. func jr(file, i)
  2073. /* DOCUMENT jr, file, i
  2074.          or _jr(file, i)
  2075.      Jump to a particular record number I (from 1 to n_records) in a
  2076.      binary file FILE.  The function returns 1 if such a record exists,
  2077.      0 if there is no such record.  In the latter case, no action is
  2078.      taken; the program halts with an error only if jr was invoked
  2079.      as a subroutine.  Record numbering wraps like array indices; use
  2080.      jr, file, 0  to jump to the last record, -1 to next to last, etc.
  2081.    SEE ALSO: jt, jc, edit_times, show
  2082.  */
  2083. {
  2084.   return _jr(file, i);
  2085. }
  2086.  
  2087. extern add_record;
  2088. /* DOCUMENT add_record, file, time, ncyc
  2089.          or add_record, file, time, ncyc, address
  2090.          or add_record, file
  2091.      adds a new record to FILE corresponding to the specified TIME and
  2092.      NCYC (respectively a double and a long).  Either or both TIME
  2093.      and NCYC may be nil or omitted, but the existence of TIME and
  2094.      NCYC must be the same for every record added to one FILE.
  2095.      If present, ADDRESS specifies the disk address of the new record,
  2096.      which is assumed to be in the current file.  Without ADDRESS, or
  2097.      if ADDRESS<0, the next available address is used; this may create
  2098.      a new file in the family (see the set_filesize function).
  2099.      The add_record function leaves the new record current
  2100.      for subsequent save commands to actually write the data.
  2101.  
  2102.      The TIME, NCYC, and ADDRESS arguments may be equal length vectors
  2103.      to add several records at once; in this case, the first of the
  2104.      newly added records is the current one.  If all three of TIME,
  2105.      NCYC, and ADDRESS are nil or omitted, no new records are added,
  2106.      but the file becomes a record file if it was not already, and in
  2107.      any case, no record will be the current record after such an
  2108.      add_record call.
  2109.  
  2110.      After the first add_record call (even if no records were added),
  2111.      subsequent add_variable commands will create record variables.
  2112.      After the first record has been added, subsequent save commands
  2113.      will create any new variables as record variables.
  2114.      After a second record has been added using add_record, neither
  2115.      save commands nor add_variable commands may be used to introduce
  2116.      any new record variables.
  2117.    SEE ALSO: save, createb, updateb, openb, set_filesize, set_blocksize
  2118.              add_variable
  2119.  */
  2120.  
  2121. extern add_variable;
  2122. /* DOCUMENT add_variable, file, address, name, type, dimlist
  2123.      adds a variable NAME to FILE at the specified ADDRESS, with the
  2124.      specified TYPE and dimensions given by DIMLIST.  The DIMLIST may
  2125.      be zero or more arguments, as for the "array" function.  If the
  2126.      ADDRESS is <0, the next available address is used. Note that,
  2127.      unlike the save command, add_variable does not actually write any
  2128.      data -- it merely changes Yorick's description of the contents of
  2129.      FILE.
  2130.      After the first add_record call, add_variable adds a variable to
  2131.      the record instead of a non-record variable.  See add_record.
  2132.    SEE ALSO: save, openb, createb, updateb, add_record,
  2133.              add_member, install_struct, data_align
  2134.  */
  2135.  
  2136. extern set_blocksize;
  2137. /* DOCUMENT set_blocksize, file, blocksize
  2138.      sets smallest cache block size for FILE to BLOCKSIZE.  BLOCKSIZE
  2139.      is rounded to the next larger number of the form 4096*2^n if
  2140.      necessary; cache blocks for this file will be multiples of
  2141.      BLOCKSIZE bytes long.  The default BLOCKSIZE is 0x4000 (16 KB).
  2142.    SEE ALSO: openb, updateb, createb, save, restore, _read, _write
  2143.  */
  2144.  
  2145. extern set_filesize;
  2146. /* DOCUMENT set_filesize, file, filesize
  2147.      sets the new family member threshhold for FILE to FILESIZE.
  2148.      Whenever a new record is added (see add_record), if the current file
  2149.      in the FILE family has at least one record and the new record would
  2150.      cause the current file to exceed FILESIZE bytes, a new family
  2151.      member will be created to hold the new record.
  2152.      The default FILESIZE is 0x400000 (4 MB).
  2153.    SEE ALSO: openb, updateb, createb, add_record
  2154.  */
  2155.  
  2156. extern get_vars;
  2157. /* DOCUMENT name_lists= get_vars(file)
  2158.      returns the lists of non-record and record variable names in the
  2159.      binary FILE.  The return value is an array of two pointers to
  2160.      arrays of type string; *name_lists(1) is the array of non-record
  2161.      variable names (or nil if there are none), *name_lists(2) is the
  2162.      array of record variable names.
  2163.      The get_addrs function returns corresponding lists of disk
  2164.      addresses; the get_member function can be used in conjunction
  2165.      with the dimsof, structof, and typeof functions to determine
  2166.      the other properties of a variable.
  2167.    SEE ALSO: openb, updateb, restore, jt, jc, has_records, get_addrs
  2168.  */
  2169.  
  2170. extern get_addrs;
  2171. /* DOCUMENT addr_lists= get_addrs(file)
  2172.      returns the byte addresses of the non-record and record variables
  2173.      in the binary file FILE, and lists of the record addresses, file
  2174.      indices, and filenames for file families with history records.
  2175.           *addr_lists(1)   absolute addresses of non-record variables
  2176.       *addr_lists(2)   relative addresses of record variables
  2177.                        (add record address to get absolute address)
  2178.          The order of these two address lists matches the
  2179.          corresponding lists of names returned by get_vars.
  2180.       *addr_lists(3)   absolute addresses of records
  2181.       *addr_lists(4)   list of file indices corresponding to
  2182.                        addr_lists(3); indices are into addr_lists(5)
  2183.       *addr_lists(5)   list of filenames in the family
  2184.    SEE ALSO: openb, updateb, restore, jt, jc, has_records, get_vars
  2185.  */
  2186.  
  2187. func has_records(file)
  2188. /* DOCUMENT has_records(file)
  2189.      returns 1 if FILE has history records, 0 if it does not.
  2190.  */
  2191. {
  2192.   return get_vars(file)(2)? 1n : 0n;
  2193. }
  2194.  
  2195. extern get_times;
  2196. extern get_ncycs;
  2197. /* DOCUMENT times= get_times(file)
  2198.             ncycs= get_ncycs(file)
  2199.      returns the list of time or ncyc values associated with the records
  2200.      if FILE, or nil if there are none.  The time values are not guaranteed
  2201.      to be precise (but they should be good to at least 6 digits or so);
  2202.      the precise time associated with each record may be stored as a record
  2203.      variable.
  2204.    SEE ALSO: collect, openb, updateb, restore, jt, jc, edit_times
  2205.  */
  2206.  
  2207. extern edit_times;
  2208. /* DOCUMENT edit_times, file
  2209.          or edit_times, file, keep_list
  2210.          or edit_times, file, keep_list, new_times, new_ncycs
  2211.      edits the records for FILE.  The KEEP_LIST is a 0-origin index list
  2212.      of records to be kept, or nil to keep all records.  The NEW_TIMES
  2213.      array is the list of new time values for the (kept) records, and
  2214.      the NEW_NCYCS array is the list of new cycle number values for the
  2215.      (kept) records.  Either NEW_TIMES, or NEW_NCYCS, or both, may be
  2216.      nil to leave the corresponding values unchanged.  If non-nil,
  2217.      NEW_TIMES and NEW_NCYCS must have the same length as KEEP_LIST,
  2218.      or, if KEEP_LIST is nil, as the original number of records in
  2219.      the file.  If KEEP_LIST, NEW_TIME, and NEW_NCYCS are all omitted
  2220.      or nil, then edit_times removes records as necessary to ensure
  2221.      that the remaining records have monotonically increasing times,
  2222.      or, if no times are present, monotonically increasing ncycs.
  2223.      (The latest record at any given time/ncyc is retained, and earlier
  2224.      records are removed.)
  2225.      In no case does edit_times change the FILE itself; only Yorick's
  2226.      in-memory model of the file is altered.
  2227.    SEE ALSO: get_times, get_ncycs, jt, jc
  2228.  */
  2229.  
  2230. extern _read;
  2231. extern _write;
  2232. /* DOCUMENT _write, file, address, expression
  2233.             _read, file, address, variable
  2234.      or nbytes= _read(file, address, variable);
  2235.      are low level read and write functions which do not "see" the
  2236.      symbol table for the binary FILE.  The ADDRESS is the byte address
  2237.      at which to begin the write or read operation.  The type and number
  2238.      of objects of the EXPRESSION or VARIABLE determines how much data
  2239.      to read, and what format conversion operations to apply.  In the
  2240.      case of type char, no conversion operations are ever applied, and
  2241.      _read will return the actual number of bytes read, which may be
  2242.      fewer than the number implied by VARIABLE in this one case.
  2243.      (In all other cases, _read returns numberof(VARIABLE).)
  2244.      If the FILE has records, the ADDRESS is understood to be in the
  2245.      file family member in which the current record resides.
  2246.    SEE ALSO: openb, createb, updateb, save, restore
  2247.  */
  2248.  
  2249. extern add_member;
  2250. /* DOCUMENT add_member, file, struct_name, offset, name, type, dimlist
  2251.      adds a member to a data type in the file FILE.  The data type name
  2252.      (struct name) is STRUCT_NAME, which will be created if it does
  2253.      not already exist.  The new member will be at OFFSET (in bytes)
  2254.      from the beginning of an instance of this structure, and will
  2255.      have the specified NAME, TYPE, and DIMLIST.  Use OFFSET -1 to
  2256.      have add_member compute the next available offset in the structure.
  2257.      The TYPE can be either a structure definition, or a string naming
  2258.      a previously defined data type in FILE.  The optional DIMLIST is
  2259.      as for the "array" function.
  2260.      The STRUCT_NAME built from a series of add_member calls cannot be
  2261.      used until it is installed with install_struct.
  2262.      This function should be used very sparingly, mostly in code which
  2263.      is building the structure of a foreign-format binary file.
  2264.    SEE ALSO: add_variable, install_struct, struct_align
  2265.  */
  2266.  
  2267. extern install_struct;
  2268. /* DOCUMENT install_struct, file, struct_name
  2269.          or install_struct, file, struct_name, size, align, order
  2270.          or install_struct, file, struct_name, size, align, order, layout
  2271.      installs the data type named STRUCT_NAME in the binary FILE.  In
  2272.      the two argument form, STRUCT_NAME must have been built by one or
  2273.      more calls to the add_member function.  In the 5 and 6 argument calls,
  2274.      STRUCT_NAME is a primitive data type -- an integer type for the 5
  2275.      argument call, and a floating point type for the 6 argument call.
  2276.      The 5 argument form may also be used to declare opaque data types.
  2277.      SIZE is the size of an instance in bytes, ALIGN is its alignment
  2278.      boundary (also in bytes), and ORDER is the byte order.  ORDER is
  2279.      1 for most significant byte first, -1 for least significant byte
  2280.      first, and 0 for opaque (unconverted) data.  Other ORDER values
  2281.      represent more complex byte permutations (2 is the byte order for
  2282.      VAX floating point numbers).  If ORDER equals SIZE, then the data
  2283.      type is not only opaque, but also must be read sequentially.
  2284.      LAYOUT is an array of 7 long values parameterizing the floating
  2285.      point format, [sign_address, exponent_address, exponent_size,
  2286.      mantissa_address, mantissa_size, mantissa_normalized, exponent_bias]
  2287.      (the addresses and sizes are in bits, reduced to MSB first order).
  2288.      Use, e.g., nameof(float) for STRUCT_NAME to redefine the meaning
  2289.      of the float data type for FILE.
  2290.    SEE ALSO: add_variable, add_member
  2291.  */
  2292.  
  2293. extern data_align;
  2294. /* DOCUMENT data_align, file, alignment
  2295.      in binary file FILE, align new variables to begin at a byte address
  2296.      which is a multiple of ALIGNMENT.  (This affects placement of data
  2297.      declared using save and add_variable.  For add_variable, data_align
  2298.      has an effect only if the address is not specified.)  If ALIGNMENT
  2299.      is <=0, new variables will be aligned as they would be if they were
  2300.      data structure members.  The default value is 0.
  2301.    SEE ALSO: save, add_variable
  2302.  */
  2303.  
  2304. extern struct_align;
  2305. /* DOCUMENT struct_align, file, alignment
  2306.      in binary file FILE, align new struct members which are themselves
  2307.      struct instances to begin at a byte address which is a multiple of
  2308.      ALIGNMENT.  (This affects members declared explicitly by add_member,
  2309.      as well as implicitly by save or add_variable.)  If ALIGNMENT is <=0,
  2310.      returns to the default for this machine.  The struct alignment is in
  2311.      addition to the alignment implied by the most restrictively aligned
  2312.      member of the struct.  Most machines want ALIGNMENT of 1.
  2313.    SEE ALSO: add_member
  2314.  */
  2315.  
  2316. extern add_next_file;
  2317. /* DOCUMENT failure= add_next_file(file, filename, create_flag)
  2318.      adds the next file to the FILE, which must contain history records.
  2319.      If FILENAME is non-nil, the new file will be called that, otherwise
  2320.      the next sequential filename is used.  If CREATE_FLAG is present
  2321.      and non-zero, the new file will be created if it does not already
  2322.      exist.  If omitted or nil, CREATE_FLAG defaults to 1 if the file has
  2323.      write permission and 0 if it does not.
  2324.      Returns 0 on success.
  2325.    SEE ALSO: openb, updateb, createb, add_record
  2326.  */
  2327.  
  2328. /*--------------------------------------------------------------------------*/
  2329.  
  2330. extern error;
  2331. extern exit;
  2332. /* DOCUMENT exit, msg
  2333.             error, msg
  2334.      Exits the current interpreted *main* program, printing the MSG.
  2335.      (MSG can be omitted to print a default.)
  2336.      In the case of exit, the result is equivalent to an immediate
  2337.      return from every function in the current calling chain.
  2338.      In the case of error, the result is the same as if an error had
  2339.      occurred in a compiled routine.
  2340.    SEE ALSO: print, write, batch
  2341.  */
  2342.  
  2343. extern batch;
  2344. /* DOCUMENT batch, 1
  2345.             batch, 0
  2346.         batch()
  2347.      turns on, turns off, or tests for batch mode, respectively.
  2348.      If yorick is started with the command line:
  2349.         yorick -batch batch_include.i ...
  2350.      then batch mode is turned on, the usual custom.i startup file is
  2351.      skipped, and the file batch_include.i is parsed and executed.  The
  2352.      -batch and batch_include.i command line arguments are removed from
  2353.      the list returned by get_argv().  These must be the first two
  2354.      arguments on the command line.
  2355.  
  2356.      In batch mode, any error will terminate Yorick (as by the quit
  2357.      function) rather than entering debug mode.
  2358.  
  2359.    SEE ALSO: process_argv, get_argv
  2360.  */
  2361.  
  2362. /*--------------------------------------------------------------------------*/
  2363.  
  2364. extern timestamp;
  2365. /* DOCUMENT timestamp()
  2366.      returns string of the form "Sun Jan  3 15:14:13 1988" -- always
  2367.      has 24 characters.
  2368.    SEE ALSO: timer
  2369.  */
  2370.  
  2371. extern timer;
  2372. /* DOCUMENT timer, elapsed
  2373.          or timer, elapsed, split
  2374.      updates the ELAPSED and optionally SPLIT timing arrays.  These
  2375.      arrays must each be of type array(double,3); the layout is
  2376.      [cpu, system, wall], with all three times measured in seconds.
  2377.      ELAPSED is updated to the total times elapsed since this copy
  2378.      of Yorick started.  SPLIT is incremented by the difference between
  2379.      the new values of ELAPSED and the values of ELAPSED on entry.
  2380.      This feature allows for primitive code profiling by keeping
  2381.      separate accounting of time usage in several categories, e.g.--
  2382.         elapsed= total= cat1= cat2= cat3= array(double, 3);
  2383.         timer, elapsed, total;
  2384.         ... category 1 code ...
  2385.     timer, elapsed, cat1;
  2386.         ... category 2 code ...
  2387.     timer, elapsed, cat2;
  2388.         ... category 3 code ...
  2389.     timer, elapsed, cat3;
  2390.         ... more category 2 code ...
  2391.     timer, elapsed, cat2;
  2392.         timer, elapsed, total;
  2393.      The wall time is not absolutely reliable, owning to possible
  2394.      rollover at midnight.
  2395.    SEE ALSO: timestamp, timer_print
  2396.  */
  2397.  
  2398. func timer_print(label, split, ..)
  2399. /* DOCUMENT timer_print, label1, split1, label2, split2, ...
  2400.          or timer_print
  2401.          or timer_print, label_total
  2402.      prints out a timing summary for splits accumulated by timer.
  2403.    SEE ALSO: timer
  2404.  */
  2405. {
  2406.   elapsed= s= array(double, 1:3);
  2407.   timer, elapsed;
  2408.   write,format="%30s     CPU sec  System sec    Wall sec\n","Timing Category";
  2409.   if (!is_void(label) && !is_void(split)) {
  2410.     s(1:3)= split;
  2411.     write,format="%30s %11.3f %11.3f %11.3f\n", label, s(1), s(2), s(3);
  2412.   }
  2413.   while (more_args()>1) {
  2414.     labl= next_arg();
  2415.     s(1:3)= next_arg();
  2416.     write,format="%30s %11.3f %11.3f %11.3f\n", labl, s(1), s(2), s(3);
  2417.   }
  2418.   if (is_void(label) || is_void(split)) {
  2419.     if (is_void(label)) labl= "-----Total Elapsed Times-----";
  2420.     else labl= label;
  2421.     s(1:3)= elapsed;
  2422.     write,format="%30s %11.3f %11.3f %11.3f\n", labl, s(1), s(2), s(3);
  2423.   }
  2424. }
  2425.  
  2426. /*--------------------------------------------------------------------------*/
  2427.  
  2428. func area(y, x)
  2429. /* DOCUMENT area(y, x)
  2430.      returns the zonal areas of the 2-D mesh (X, Y).  If Y and X are
  2431.      imax-by-jmax, the result is (imax-1)-by-(jmax-1).  The area is
  2432.      positive when, say, X increases with i and Y increases with j.
  2433.      For example, area([[0,0],[1,1]],[[0,1],[0,1]]) is +1.
  2434.    SEE ALSO: volume
  2435.  */
  2436. { return x(dif,zcen)*y(zcen,dif) - x(zcen,dif)*y(dif,zcen); }
  2437.  
  2438. func volume(r, z)
  2439. /* DOCUMENT volume(r, z)
  2440.      returns the zonal volumes of the 2-D cylindrical mesh (R, Z).
  2441.      If R and Z are imax-by-jmax, the result is (imax-1)-by-(jmax-1).
  2442.      The volume is positive when, say, Z increases with i and R increases
  2443.      with j.  For example, volume([[0,0],[1,1]],[[0,1],[0,1]]) is +pi.
  2444.    SEE ALSO: area
  2445.  */
  2446. {
  2447.   s= r*r;
  2448.   v= z(dif,zcen)*s(zcen,dif) - z(zcen,dif)*s(dif,zcen);
  2449.   s= z*r;
  2450.   return (2.0*pi/3.0)*(v+s(dif,zcen)*r(zcen,dif)-s(zcen,dif)*r(dif,zcen));
  2451. }
  2452.  
  2453. func ptcen(zncen, ireg)
  2454. /* DOCUMENT ptcen(zncen)
  2455.          or ptcen(zncen, ireg)
  2456.      returns point centered version of the 2-D zone centered array ZNCEN.
  2457.      The result is imax-by-jmax if ZNCEN is (imax-1)-by-(jmax-1).
  2458.      If the region number array IREG is specified, zones with region
  2459.      number 0 are not included in the point centering operation.
  2460.      Note that IREG should have dimensions imax-by-jmax; the first
  2461.      row and column of IREG are ignored.
  2462.      Without IREG, ptcen(zncen) is equivalent to zncen(pcen,pcen).
  2463.   SEE ALSO: zncen, uncen
  2464.  */
  2465. {
  2466.   if (is_void(ireg)) return zncen(pcen, pcen, ..);
  2467.   void= use_origins(0);
  2468.   exist= (ireg(2:,2:)!=0);
  2469.   return (exist*zncen)(pcen,pcen,..)/(exist(pcen,pcen)+1.e-35);
  2470. }
  2471.  
  2472. func zncen(ptcen, ireg)
  2473. /* DOCUMENT zncen(ptcen)
  2474.          or zncen(ptcen, ireg)
  2475.      returns zone centered version of the 2-D point centered array PTCEN.
  2476.      The result is (imax-1)-by-(jmax-1) if PTCEN is imax-by-jmax.
  2477.      If the region number array IREG is specified, zones with region
  2478.      number 0 are not included in the point centering operation.
  2479.      Note that IREG should have dimensions imax-by-jmax, like
  2480.      the input PTCEN array; the first row and column of IREG are ignored.
  2481.      Without IREG, zncen(ptcen) is equivalent to ptcen(zcen,zcen).
  2482.   SEE ALSO: ptcen, uncen
  2483.  */
  2484. {
  2485.   if (is_void(ireg)) return ptcen(zcen, zcen, ..);
  2486.   void= use_origins(0);
  2487.   exist= (ireg(2:,2:)!=0);
  2488.   return exist*ptcen(zcen, zcen, ..);
  2489. }
  2490.  
  2491. func uncen(ptcen, ireg)
  2492. /* DOCUMENT uncen(ptcen)
  2493.          or uncen(ptcen, ireg)
  2494.      returns zone centered version of the 2-D zone centered array PTCEN.
  2495.      The result is (imax-1)-by-(jmax-1) if PTCEN is imax-by-jmax.
  2496.      If the region number array IREG is specified, zones with region
  2497.      number 0 are not included in the point centering operation.
  2498.      Note that IREG should have dimensions imax-by-jmax, like
  2499.      the input PTCEN array; the first row and column of IREG are ignored.
  2500.      Without IREG, uncen(ptcen) is equivalent to ptcen(uncp,uncp).
  2501.  
  2502.      Do not use uncen to zone center data which is naturally point
  2503.      centered -- use the zncen function for that purpose.  The uncen
  2504.      function is the (nearly) exact inverse of the ptcen function,
  2505.      so that uncen(ptcen(zncen, ireg), ireg) will return the original
  2506.      zncen array.  The uncen reconstruction is as exact as possible,
  2507.      given the finite precision of floating point operations.
  2508.   SEE ALSO: ptcen, zncen
  2509.  */
  2510. {
  2511.   if (is_void(ireg)) return ptcen(uncp, uncp, ..);
  2512.   void= use_origins(0);
  2513.   exist= (ireg(2:,2:)!=0);
  2514.   return (exist(pcen,pcen)*ptcen)(uncp, uncp, ..);
  2515. }
  2516.  
  2517. /*--------------------------------------------------------------------------*/
  2518.  
  2519. func call(void)
  2520. /* DOCUMENT call, subroutine(arg1, arg2, arg3, arg4, arg5
  2521.                              arg6, arg7, arg8);
  2522.      allows a SUBROUTINE to be called with a very long argument list
  2523.      as an alternative to:
  2524.           subroutine, arg1, arg2, arg3, arg4, arg5,
  2525.             arg6, arg7, arg8;
  2526.      Note that the statement
  2527.           subroutine(arg1, arg2, arg3, arg4, arg5,
  2528.                      arg6, arg7, arg8);
  2529.      will print the return value of subroutine, even if it is nil.
  2530.      If invoked as a function, call simply returns its argument.
  2531.  */
  2532. { return void; }
  2533.  
  2534. extern symbol_def;
  2535. /* DOCUMENT symbol_def(func_name)(arglist)
  2536.          or symbol_def(var_name)
  2537.      invokes the function FUNC_NAME with the specified ARGLIST,
  2538.      returning the return value.  ARGLIST may be zero or more arguments.
  2539.      In fact, symbol_def("fname")(arg1, arg2, arg3) is equivalent to
  2540.      fname(arg1, arg2, arg3), so that "fname" can be the name of any
  2541.      variable for which the latter syntax is meaningful -- interpreted
  2542.      function, built-in function, or array.
  2543.  
  2544.      Without an argument list, symbol_def("varname") is equivalent to
  2545.      varname, which allows you to get the value of a variable whose name
  2546.      you must compute.
  2547.  
  2548.      DO NOT OVERUSE THIS FUNCTION.  It works around a specific deficiency
  2549.      of the Yorick language -- the lack of pointers to functions -- and
  2550.      should be used for such purposes as hook lists (see openb).
  2551.  
  2552.    SEE ALSO: symbol_set
  2553.  */
  2554.  
  2555. extern symbol_set;
  2556. /* DOCUMENT symbol_set, var_name, value
  2557.      is equivalent to the redefinition
  2558.           varname= value
  2559.      except that var_name="varname" is a string which must be computed.
  2560.  
  2561.      DO NOT OVERUSE THIS FUNCTION.  It works around a specific deficiency
  2562.      of the Yorick language -- the lack of pointers to functions, streams,
  2563.      bookmarks, and other special non-array data types.
  2564.  
  2565.    SEE ALSO: symbol_def
  2566.  */
  2567.  
  2568. /*--------------------------------------------------------------------------*/
  2569.  
  2570. extern dbexit;
  2571. extern dbcont;
  2572. extern dbret;
  2573. extern dbskip;
  2574. extern dbup;
  2575. extern dbinfo;
  2576. extern dbdis;
  2577. extern dbauto;
  2578. /* DOCUMENT Debug mode.
  2579.  
  2580.    Yorick errors fall into two general categories: Syntax errors discovered
  2581.    during parsing, and runtime errors discovered when a Yorick program is
  2582.    actually running.  When a runtime error occurs, Yorick offers the
  2583.    choice of entering "debug mode", which you can do by typing the <RETURN>
  2584.    key immediately after the error occurs.  Typing a non-blank line exits
  2585.    debug mode automatically by default.  In debug mode, the Yorick prompt
  2586.    becomes "dbug>" instead of the usual ">".  When you see this prompt,
  2587.    Yorick has halted "in the middle of" the function in which the error
  2588.    occurred, and you can print, plot, modify, or save the local variables
  2589.    in that function by means of ordinary Yorick commands.  Debug mode is
  2590.    recursive; that is, you can debug an error which occurred during
  2591.    debugging to any number of levels.
  2592.  
  2593.    You can exit from debug mode in several ways:
  2594.  
  2595.       dbexit            -- exit current debug level, discarding all
  2596.                            active functions and their local variables
  2597.       dbexit, 0         -- exit all debug levels
  2598.       dbexit, n         -- exit (at most) N debug levels
  2599.  
  2600.       dbcont            -- continue execution of the current function
  2601.          Continuing is useful if you have managed to repair the
  2602.      problem which caused the error.  The expression in which the
  2603.      error occurred will be evaluated a second time, so beware of
  2604.      side effects.
  2605.  
  2606.       dbret, value      -- continue execution by returning VALUE (which
  2607.                            may be nil or omitted) to the caller of the
  2608.                function in which the error occurred.
  2609.      This is useful if the function in which the error occurred is
  2610.      hopelessly confounded, but you know the value it should return.
  2611.  
  2612.    Yorick does not allow "single stepping" directly, although you can
  2613.    execute the statements in a function by copying them, then tell
  2614.    Yorick to skip those statements you have executed "by hand".  There
  2615.    are two functions for skipping execution:
  2616.  
  2617.       dbskip            -- skip the next logical line (This will be only
  2618.                            a portion of a source line if several statements
  2619.                are stacked on the source line.)
  2620.       dbskip, n         -- skip next N (positive or negative) logical lines
  2621.  
  2622.       dbup              -- discard the current function, so that you are
  2623.                            debugging its caller -- there is no way to go
  2624.                back "down", so be careful
  2625.  
  2626.    There are two functions which print information (like other print
  2627.    functions, if called as functions instead of subroutines, their
  2628.    result is returned as a string array with one line per string):
  2629.  
  2630.       dbinfo            -- returns current function and source line
  2631.  
  2632.       dbdis             -- returns disassembled virtual machine code
  2633.                            for the next line (use the disassemble function
  2634.                to get the entire function)
  2635.      This allows you to see exactly where in a line the error occurred.
  2636.  
  2637.    Finally,
  2638.  
  2639.       dbauto            -- toggles whether debug mode will be entered
  2640.                            automatically when a runtime error occurs
  2641.       dbauto, 1         -- enter debug mode automatically after an error
  2642.       dbauto, 0         -- type <RETURN> after error to enter debug mode
  2643.  */
  2644.  
  2645. /*--------------------------------------------------------------------------*/
  2646.